0
|
1 package suikwasha.distributedalgorithm.simulator;
|
|
2
|
|
3 import java.util.concurrent.CountDownLatch;
|
|
4 import java.util.concurrent.atomic.AtomicLong;
|
|
5
|
|
6 public class Synchronizer
|
|
7 {
|
|
8 private AtomicLong counter;
|
|
9 private CountDownLatch latch;
|
|
10
|
|
11 public Synchronizer()
|
|
12 {
|
|
13 counter = new AtomicLong();
|
|
14 latch = new CountDownLatch(1);
|
|
15 }
|
|
16
|
|
17 public long countup() throws IllegalStateException
|
|
18 {
|
|
19 // double checking , is it effective?
|
|
20 if(latch.getCount() != 0){
|
|
21 long value = counter.incrementAndGet();
|
|
22 if(latch.getCount() != 0){
|
|
23 return value;
|
|
24 }
|
|
25 }
|
|
26
|
|
27 throw new IllegalStateException("latch.getCount() == 0");
|
|
28 }
|
|
29
|
|
30 public long countdown() throws IllegalStateException
|
|
31 {
|
|
32 long value = counter.decrementAndGet();
|
|
33 if(value < 0){
|
|
34 throw new IllegalStateException("counter < 0");
|
|
35 }
|
|
36
|
|
37 if(value == 0){
|
|
38 latch.countDown();
|
|
39 }
|
|
40
|
|
41 return value;
|
|
42 }
|
|
43
|
|
44 public void await() throws InterruptedException
|
|
45 {
|
|
46 latch.await();
|
|
47 }
|
|
48 }
|