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