comparison src/main/java/suikwasha/distributedalgorithm/simulator/Synchronizer.java @ 0:38a110b13db1

added SimpleDistributedAlgorithmFramework. added NaiveAlgorithm added ChangRobertsAlgorithm added PertersonAlgorithm
author suikwasha
date Fri, 19 Oct 2012 00:05:41 +0900
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:38a110b13db1
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 }