private void addInterest(SelectableChannel channel,int operation,ISelectHandler callback) throws ClosedChannelException {
  SelectionKey key=channel.keyFor(selector);
  if (key == null) {
    channel.register(selector,operation,callback);
  }
 else   if (!key.isValid()) {
    throw new RuntimeException(String.format("Unable to add %d in %s due to key is invalid",operation,channel));
  }
 else {
    if ((key.interestOps() & operation) != 0) {
      throw new RuntimeException(String.format("%d has been registered in %s",operation,channel));
    }
    if (key.attachment() == null) {
      key.attach(callback);
    }
 else {
      if (callback != key.attachment()) {
        throw new RuntimeException("Unmatched SelectHandler has already been attached" + " for other operation");
      }
    }
    key.interestOps(key.interestOps() | operation);
  }
}

private void addInterest ( SelectableChannel channel , int operation , ISelectHandler callback ) throws ClosedChannelException { SelectionKey key = channel . keyFor ( selector ) ; if ( key == null ) { channel . register ( selector , operation , callback ) ; } else if ( ! key . isValid ( ) ) { throw new RuntimeException ( String . format ( "Unable to add %d in %s due to key is invalid" , operation , channel ) ) ; } else { if ( ( key . interestOps ( ) & operation ) != 0 ) { throw new RuntimeException ( String . format ( "%d has been registered in %s" , operation , channel ) ) ; } if ( key . attachment ( ) == null ) { key . attach ( callback ) ; } else { if ( callback != key . attachment ( ) ) { throw new RuntimeException ( "Unmatched SelectHandler has already been attached" + " for other operation" ) ; } } key . interestOps ( key . interestOps ( ) | operation ) ; } }
register an operation interest on a selectablechannel , with iselecthandler as callback attachment there are two cases when trying to register an interest 1 . the whole key does not exist ; no interests ever registered for this channel 2 . the key exists due to other interests registered but not the one we are adding < p > in 1st case , we just register this channel with operation on the given selector in 2nd case , we have to make sure the state of niolooper is clean : 1 . key has to be valid 2 . the interest has not yet been registered 3 . if old attached iselecthandler exists , it has to be the same as new one if any one of above 3 conditions are not met , runtimeexception would be thrown .
