view src/main/java/suikwasha/distributedalgorithm/framework/Selector.java @ 2:8e1f63faa2fd default tip

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

package suikwasha.distributedalgorithm.framework;

import java.util.LinkedList;
import java.util.concurrent.SynchronousQueue;

public class Selector
{
	private final SynchronousQueue<Port> queue;
	private final LinkedList<Port> watchList;
	
	public Selector()
	{
		queue = new SynchronousQueue<Port>();
		watchList = new LinkedList<Port>();
	}
	
	public void signal(Port _p)
	{
		queue.offer(_p);
	}
	
	public void register(Port _p)
	{
		watchList.add(_p);
	}
	
	public Port select() throws InterruptedException
	{
		Port availablePort;
		int length = watchList.size();
		for(int i = 0;i < length;i ++){
			availablePort = watchList.poll();
			if(availablePort.isReady()){
				watchList.addLast(availablePort);
				return availablePort;
			}
			watchList.addLast(availablePort);
		}
		
		return queue.take();
	}
}