Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 15th, 2012  |  syntax: None  |  size: 1.01 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Java NIO Selector select() returns 0 although channels are ready
  2. Selector selector = Selector.open();
  3.  
  4. SocketChannel channel;
  5.  
  6. for (...) { // for each node
  7.   // Create and connect channels...
  8.   ...
  9.  
  10.   channel.configureBlocking(false);
  11.   channel.register(selector, SelectionKey.OP_READ, someRelatedObject);
  12. }
  13.  
  14. int ready;
  15. Set<SelectionKey> readyKeys;
  16. while (true) {
  17.   ready = selector.select();
  18.   readyKeys = selector.selectedKeys();
  19.  
  20.   System.out.println("Ready channels: " + ready);
  21.   System.out.println("Selected channels: " + readyKeys.size());
  22.  
  23.   if (ready == 0) {
  24.     continue;
  25.   }
  26.  
  27.   for (SelectionKey key : readyKeys) {
  28.     if (key.isValid() && key.isReadable()) {
  29.       // Take action...
  30.     }
  31.  
  32.     readyKeys.remove(key);
  33.   }
  34. }
  35.        
  36. for (SelectionKey key : readyKeys) {
  37.     if (key.isValid() && key.isReadable()) {
  38.       // Take action...
  39.     }
  40.  
  41.     readyKeys.remove(key);
  42.   }
  43.        
  44. for (SelectionKey key : readyKeys) {
  45.     readyKeys.remove(key);
  46.  
  47.     if (key.isValid() && key.isReadable()) {
  48.       // Take action...
  49.     }
  50.   }