Mercurial > hg > Members > shoshi > distributedalgorithm
diff 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 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/suikwasha/distributedalgorithm/simulator/Synchronizer.java Fri Oct 19 00:05:41 2012 +0900 @@ -0,0 +1,48 @@ +package suikwasha.distributedalgorithm.simulator; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicLong; + +public class Synchronizer +{ + private AtomicLong counter; + private CountDownLatch latch; + + public Synchronizer() + { + counter = new AtomicLong(); + latch = new CountDownLatch(1); + } + + public long countup() throws IllegalStateException + { + // double checking , is it effective? + if(latch.getCount() != 0){ + long value = counter.incrementAndGet(); + if(latch.getCount() != 0){ + return value; + } + } + + throw new IllegalStateException("latch.getCount() == 0"); + } + + public long countdown() throws IllegalStateException + { + long value = counter.decrementAndGet(); + if(value < 0){ + throw new IllegalStateException("counter < 0"); + } + + if(value == 0){ + latch.countDown(); + } + + return value; + } + + public void await() throws InterruptedException + { + latch.await(); + } +}