view src/pathfinder/mergetest/SelectorSimulator.java @ 157:1a2269c820df simulator2008-8-26

*** empty log message ***
author pin
date Tue, 26 Aug 2008 18:15:00 +0900
parents 0dfb6413a31e
children
line wrap: on
line source

package pathfinder.mergetest;

import java.util.ArrayList;
import java.util.Set;

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

	public int select(){
		selectedKeys = new ArrayList<SelectionKeySimulator<P>>();
		
		synchronized(ns){
			boolean empty = true;
			//while(empty){
				for(SelectionKeySimulator<P> key : keyList){
					ChannelSimulator<P> channel = key.channel();
//					if(channel.readQisEmpty()){
//						empty = true;
//					}else{
//						empty = false;
//						selectedKeys.add(key);
//						break;
//					}
					if(!channel.readQisEmpty()){
						empty = false;
						selectedKeys.add(key);
					}
				}

				try {
					if(empty) ns.wait();
				} catch (InterruptedException e) {
					//e.printStackTrace();
				}
			//}
		}
		return selectedKeys.size();
	}
	
	public SelectionKeySimulator<P> register(ChannelSimulator<P> cs){
		SelectionKeySimulator<P> key = new SelectionKeySimulator<P>(cs);
		keyList.add(new SelectionKeySimulator<P>(cs));
		return key;
	}
	
	public SelectionKeySimulator<P> register(ChannelSimulator<P> cs, int opt, Object handler){
		SelectionKeySimulator<P> key = new SelectionKeySimulator<P>(cs);
		key.attach(handler);
		keyList.add(key);
		return key;
	}

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

}