tags:

views:

398

answers:

1

Please point/provide me an working example of selector.wakeup(); method between two threads.

I tried to create a simple program where a thread is waiting on selector.select() method. Second thread creates some sockets and tries to register with the selector; on which the first thread is blocked.

Hence I need to use selector's wakeup method, but somehow the first thread isnt doesn't come out of blocking mode.

The javadoc of wakeup method states:

If another thread is currently blocked in an invocation of the Selector.select() or Selector.select(long) methods then that invocation will return immediately.

P.S There are few other work-around; one of them is select(timeout) but I am trying to figure out where the mistake is.

The psuedo-code:

FIRST THREAD:

static Selector selector = Selector.open();
while(true) {
   int n = selectorGlobal.select();
   selectorKeySet = selectorGlobal.selectedKeys().iterator();
   while (selectorKeySet.hasNext()) {
      selectionKey = selectorKeySet.next();
      if (selectionKey.isReadable()) {
         //do something
      }
      if(selectionKey.isAcceptable()) {
         //accept
      }
   }
}

SECOND THREAD:

while (itr.hasNext()) { 
   data = (String) itr.next();
   String IP = data.get(0);
   String Port = data.get(1);

   SocketChannel socketChannel = SocketChannel.open();
   socketChannel.configureBlocking(true);
   boolean isConnected = socketChannel.connect(new InetSocketAddress(IP, Port));
   ClassName.selector.wakeup();
   SelectionKey selectionKey = SelectSockets.registerChannel(ClassName.selector,
                socketChannel, SelectionKey.OP_READ);

}
A: 
Seth
Thank you Seth. Connecting to other sockets is an activity which would be happening very rarely; hence I wished somehow the selector thread would not check some collection/variable everytime there is activity on selection keys.
Nilesh