Example usage for java.nio.channels SelectableChannel keyFor

List of usage examples for java.nio.channels SelectableChannel keyFor

Introduction

In this page you can find the example usage for java.nio.channels SelectableChannel keyFor.

Prototype

public abstract SelectionKey keyFor(Selector sel);

Source Link

Document

Retrieves the key representing the channel's registration with the given selector.

Usage

From source file:com.alibaba.napoli.gecko.core.nio.impl.Reactor.java

final void unregisterChannel(final SelectableChannel channel) {
    try {//from   w w w . j  ava  2s  .  c  o  m
        final Selector selector = this.selector;
        if (selector != null) {
            if (channel != null) {
                final SelectionKey key = channel.keyFor(selector);
                if (key != null) {
                    key.cancel();
                    this.cancelledKeys++;
                }
            }
        }
        if (channel != null && channel.isOpen()) {
            channel.close();
        }
    } catch (final Throwable t) {
        // ignore
    }
    this.wakeup();
}

From source file:com.byteatebit.nbserver.simple.SelectorTask.java

@Override
public SelectionKey register(SelectableChannel channel, int ops, IOTask nioTask, IOTimeoutTask timeoutTask,
        long timeoutMs) {
    Preconditions.checkNotNull(channel, "channel cannot be null");
    Preconditions.checkNotNull(nioTask, "nioTask cannot be null");
    IOTimeoutTask ioTimeoutTask = timeoutTask == null ? defaultIoTimeoutTask : timeoutTask;
    if (LOG.isDebugEnabled())
        LOG.debug("registering channel " + channel + "for ops " + ops + " and task " + nioTask);
    SelectionKey key = null;//from   ww  w .j a v  a2  s .com
    NioSelectionKeyEntry selectionKeyEntry = null;
    synchronized (this) {
        try {
            key = channel.keyFor(selector);
            if (key != null) {
                key.interestOps(key.interestOps() | ops);
                selectionKeyEntry = (NioSelectionKeyEntry) key.attachment();
            } else {
                selectionKeyEntry = new NioSelectionKeyEntry();
                key = channel.register(selector, ops, selectionKeyEntry);
            }
        } catch (ClosedChannelException e) {
            throw new SelectorException(e);
        }
        selectionKeyEntry.setTask(nioTask, ioTimeoutTask, ops, timeoutMs);
    }
    if (LOG.isDebugEnabled())
        LOG.debug("Total number of selection keys: " + selector.keys().size());
    return key;
}