code: 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 {
        // Key is not null and key is valid
        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");
          }
          // If call == key.attachment
          // Just skip
        }
        key.interestOps(key.interestOps() | operation);
      }
    }
docs: 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.
  
  @param channel The Selectable to register operation interest
  @param operation The operation interest to register
  @param callback The Callback to handle
  @throws ClosedChannelException if Channel is closed when trying to register an interest