summaryrefslogtreecommitdiff
path: root/src/main/java/com/keuin/kbackupfabric/operation/abstracts/InvokableAsyncBlockingOperation.java
blob: 6268d5a81cb46516e59f63f12082b034880be422 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.keuin.kbackupfabric.operation.abstracts;

import com.keuin.kbackupfabric.operation.abstracts.i.Blocking;
import com.keuin.kbackupfabric.operation.abstracts.i.Invokable;

public abstract class InvokableAsyncBlockingOperation implements Invokable, Blocking {

    private final InvokableAsyncOperation asyncOperation;
    private final HackedBlockingOperation blockingOperation;

    public InvokableAsyncBlockingOperation(String name) {
        asyncOperation = new InvokableAsyncOperation(name) {
            @Override
            protected void async() {
                InvokableAsyncBlockingOperation.this.async();
                // When the async operation finishes, unblock
                blockingOperation.noUnblocking(false);
                blockingOperation.block(false);
            }

            @Override
            protected boolean sync() {
                return InvokableAsyncBlockingOperation.this.sync();
            }
        };

        blockingOperation = new HackedBlockingOperation();
    }

    @Override
    public boolean invoke() {
        return blockingOperation.invoke();
    }

    @Override
    public boolean isBlocked() {
        return blockingOperation.isBlocked();
    }

    protected abstract void async();

    protected boolean sync() {
        return true;
    }

    private class HackedBlockingOperation extends InvokableBlockingOperation {

        @Override
        protected boolean blockingContext() {

            noUnblocking(true);
            return asyncOperation.invoke();
        }

        @Override
        public void noUnblocking(boolean b) {
            super.noUnblocking(b);
        }

        @Override
        public void block(boolean blockState) {
            super.block(blockState);
        }
    }

}