view src/main/java/suikwasha/distributedalgorithm/simulator/Synchronizer.java @ 2:8e1f63faa2fd default tip

added Franklin's Algorithm
author suikwasha
date Tue, 23 Oct 2012 16:49:26 +0900
parents 38a110b13db1
children
line wrap: on
line source

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();
	}
}