view src/pathfinder/mergetest/channels/SelectorSimulator.java @ 164:5c458f1a7679

*** empty log message ***
author tkaito
date Thu, 28 Aug 2008 22:18:28 +0900
parents 66e9cebce3fa
children
line wrap: on
line source

package pathfinder.mergetest.channels;

import java.io.IOException;
import java.util.ArrayList;
//import java.util.Set; //書き直す?



public class SelectorSimulator<P> {
	
	private ArrayList<SelectionKeySimulator<P>> keyList;
	private ArrayList<SelectionKeySimulator<P>> selectedKeys;
	
	public SelectorSimulator() {
		// TODO Auto-generated constructor stub
		keyList = new ArrayList<SelectionKeySimulator<P>>();
	}

	public int select() throws IOException {
		selectedKeys = new ArrayList<SelectionKeySimulator<P>>();
		
		synchronized(this) {

			while(selectedKeys.isEmpty()){
				for(SelectionKeySimulator<P> key : keyList){
					if(key.isAble())
						selectedKeys.add(key);
				}

				if(selectedKeys.isEmpty())
					try {
						this.wait();
					} catch (InterruptedException e) {
						throw new IOException("Error, Selector was interrupted!");
					}
			}
		}
		return selectedKeys.size();
	}
	
	public SelectionKeySimulator<P> register(SelectableChannelSimulator<P> cs, int opt){
		SelectionKeySimulator<P> key = new SelectionKeySimulator<P>(cs, opt);
		keyList.add(key);
		return key;
	}
	
	public SelectionKeySimulator<P> register(ChannelSimulator<P> cs, int opt, Object handler){
		SelectionKeySimulator<P> key = new SelectionKeySimulator<P>(cs, opt);
		key.attach(handler);
		keyList.add(key);
		return key;
	}

	public ArrayList<SelectionKeySimulator<P>> selectedKeys() {
		
		return selectedKeys;
	}
	
	public SelectionKeySimulator<P> getKey(ChannelSimulator<P> channel){
		for(SelectionKeySimulator<P> key : keyList){
			if(key.channel() == channel)
				return key;
		}
		return null;
	}

}