Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

how can I use a Selector in a thread safe way?

843790Jan 28 2009 — edited Jan 29 2009
Hello,

I'm using a server socket with a java.nio.channels.Selector contemporarily by 3 different threads (this number may change in the future).

From the javadoc: Selectors are themselves safe for use by multiple concurrent threads; their key sets, however, are not.

Following this advise, I wrote code in this way:
	    List keys = new LinkedList(); //private key list for each thread
	    while (true) {
		keys.clear();
		synchronized(selector) {
		    int num = selector.select();
		    if (num == 0)
			continue;
		    Set selectedKeys = selector.selectedKeys();
		    //I expected this code to produce disjoint key sets on each thread...
		    keys.addAll(selectedKeys);
		    selectedKeys.clear();
		}
		Iterator it = keys.iterator();
		while (it.hasNext()) {
		    SelectionKey key = (SelectionKey) it.next();
		    if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
			Socket s = serverSocket.accept();
			SocketChannel sc = s.getChannel();
			sc.configureBlocking( false );
			sc.register( selector, SelectionKey.OP_READ );
		    } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {

//.....
Unfortunately synchronizing on the selector didn't have the effect I expected. When another thread select()s, it sees the same key list as the other thread that select()ed previously. When control arrives to serverSocket.accept(), one thread goes ahead and the other two catch an IllegalBlockingModeException.

I'm not willing to handle this exception, the right thing to do is giving disjoint key sets to each thread. How can I achieve this goal?

Thanks in advance
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 26 2009
Added on Jan 28 2009
7 comments
1,086 views