summaryrefslogtreecommitdiff
path: root/src/main/java/com/keuin/kbackupfabric/operation/abstracts/AbstractBlockingOperation.java
blob: de672cd14205b1e9ddd5ffbd8444009dda5caad0 (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
package com.keuin.kbackupfabric.operation.abstracts;

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

public abstract class AbstractBlockingOperation extends AbstractSerializedOperation implements Blocking {

    private static final Object sync = new Object();
    private static boolean isBlocking = false;
    private boolean wasBlocked = false;
    private boolean noUnblocking = false;

    @Override
    protected final boolean operate() {
        synchronized (sync) {
            if (isBlocking) {
                System.out.println("blocked.");
                wasBlocked = true;
                return false;
            } else {
                System.out.println("not blocked.");
                wasBlocked = false;
                isBlocking = true;
            }
        }
        boolean exitCode = blockingContext();
        if (!noUnblocking)
            isBlocking = false;
        return exitCode;
    }

    public final boolean isBlocked() {
        return wasBlocked;
    }

    protected final void block(boolean blockState) {
        isBlocking = blockState;
    }

    protected void noUnblocking(boolean b) {
        noUnblocking = b;
    }

    protected boolean blockAndGet() {
        synchronized (sync) {
            boolean b = isBlocking;
            isBlocking = true;
            return b;
        }
    }

    /**
     * Implement your blocked operation here.
     *
     * @return the stat code.
     */
    protected abstract boolean blockingContext();

}