+/EE360P

distributed systems

git clone https://git.julia.blue/+/EE360P

Joseph RyanFinish 1b77db134

master
1.3 KiB45 linesraw
1public class MonitorCyclicBarrier {
2    int n, in, out;
3    Object canEnter;
4    Object canExit;
5    public MonitorCyclicBarrier(int parties) {
6        out = n = parties;
7        in = 0;
8        canEnter = new Object();
9        canExit = new Object();
10    }
11
12    public int await() throws InterruptedException {
13        final int index;
14        final long threadNum = Thread.currentThread().getId();
15        synchronized (canEnter) {
16            while (out < n) {
17                // System.out.println("Thread " + threadNum + " waiting on " +
18                //                    (n - out) + " threads to leave");
19                canEnter.wait();
20            }
21        }
22
23        synchronized (canExit) {
24            index = in++;
25            // System.out.println("Thread " + threadNum + " is index " + index)
26            while (in < n) { canExit.wait(); }
27            if (out == n) {
28                // System.out.println(index + " is the first one out");
29                out = 0;
30            }
31            canExit.notifyAll();
32        }
33
34        synchronized (canEnter) {
35            ++out;
36            // System.out.println(index + " leaving");
37            if (out == n) {
38                in = 0;
39                canEnter.notifyAll();
40                // System.out.println(index + " is the last one out");
41            }
42        }
43        return index;
44    }
45}