Example usage for java.nio.channels SelectionKey attachment

List of usage examples for java.nio.channels SelectionKey attachment

Introduction

In this page you can find the example usage for java.nio.channels SelectionKey attachment.

Prototype

Object attachment

To view the source code for java.nio.channels SelectionKey attachment.

Click Source Link

Usage

From source file:ee.ria.xroad.proxy.clientproxy.FastestSocketSelector.java

SocketInfo select() throws IOException {
    log.trace("select()");

    Selector selector = Selector.open();

    SocketInfo selectedSocket = initConnections(selector);
    if (selectedSocket != null) {
        return selectedSocket;
    }/* www  .j  a va2s .c  o  m*/

    URI selectedAddress = null;
    SocketChannel channel = null;
    try {
        SelectionKey key = selectFirstConnectedSocketChannel(selector);
        if (key == null) {
            return null;
        }

        channel = (SocketChannel) key.channel();
        selectedAddress = (URI) key.attachment();
    } finally {
        try {
            closeSelector(selector, channel);
        } catch (Exception e) {
            log.error("Error while closing selector", e);
        }
    }

    if (channel != null) {
        channel.configureBlocking(true);
        return new SocketInfo(selectedAddress, channel.socket());
    }

    return null;
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.IncomingConnectionThread.java

@Override
public void run() {

    while (!this.isInterrupted()) {

        synchronized (this.pendingReadEventSubscribeRequests) {
            while (!this.pendingReadEventSubscribeRequests.isEmpty()) {
                final SelectionKey key = this.pendingReadEventSubscribeRequests.poll();
                final IncomingConnection incomingConnection = (IncomingConnection) key.attachment();
                final SocketChannel socketChannel = (SocketChannel) key.channel();

                try {
                    final SelectionKey newKey = socketChannel.register(this.selector, SelectionKey.OP_READ);
                    newKey.attach(incomingConnection);
                } catch (ClosedChannelException e) {
                    incomingConnection.reportTransmissionProblem(key, e);
                }/* www .j av a2  s  .  c  om*/
            }
        }

        try {
            this.selector.select(500);
        } catch (IOException e) {
            LOG.error(e);
        }

        final Iterator<SelectionKey> iter = this.selector.selectedKeys().iterator();

        while (iter.hasNext()) {
            final SelectionKey key = iter.next();

            iter.remove();
            if (key.isValid()) {
                if (key.isReadable()) {
                    doRead(key);
                } else if (key.isAcceptable()) {
                    doAccept(key);
                } else {
                    LOG.error("Unknown key: " + key);
                }
            } else {
                LOG.error("Received invalid key: " + key);
            }
        }
    }

    // Do cleanup, if necessary
    if (this.listeningSocket != null) {
        try {
            this.listeningSocket.close();
        } catch (IOException ioe) {
            // Actually, we can ignore this exception
            LOG.debug(ioe);
        }
    }

    // Finally, close the selector
    try {
        this.selector.close();
    } catch (IOException ioe) {
        LOG.debug(StringUtils.stringifyException(ioe));
    }
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java

private void doRead(SelectionKey key) {

    final SocketChannel socketChannel = (SocketChannel) key.channel();
    final OutgoingConnection outgoingConnection = (OutgoingConnection) key.attachment();
    final ByteBuffer buf = ByteBuffer.allocate(8);

    try {/*from   w  w w. j a  v a 2  s. c o  m*/

        if (socketChannel.read(buf) == -1) {
            outgoingConnection.reportTransmissionProblem(new IOException("Read unexpected EOF from channel"));
        } else {
            LOG.error("Outgoing connection read real data from channel");
        }
    } catch (IOException ioe) {
        outgoingConnection.reportTransmissionProblem(ioe);
    }
}

From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkServer.java

/**
 * ??, SessiononRead, ?Session?/*w  w  w .j  a v a  2s. c  o  m*/
 * @param key
 * @throws IOException
 * @throws InterruptedException
 */
private void onRead(SelectionKey key) throws IOException {
    Session session = (Session) key.attachment();
    try {
        session.onRead();
    } catch (InterruptedException e) {
        logger.error("OOPS Exception:", e);
        Thread.currentThread().interrupt();
    }
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java

public void unsubscribeFromWriteEvent(SelectionKey selectionKey) throws IOException {

    final SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
    final OutgoingConnection outgoingConnection = (OutgoingConnection) selectionKey.attachment();

    final SelectionKey newSelectionKey = socketChannel.register(this.selector, SelectionKey.OP_READ);
    newSelectionKey.attach(outgoingConnection);
    outgoingConnection.setSelectionKey(newSelectionKey);

    synchronized (this.connectionsToClose) {
        this.connectionsToClose.put(outgoingConnection, Long.valueOf(System.currentTimeMillis()));
    }//from   w  w w  .  j av a  2s.c om
}

From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkServer.java

/**
 * ??, SessiononWrite, Session??//from   w ww. java  2s.co  m
 * @param key
 * @throws IOException
 */
private void onWrite(SelectionKey key) throws IOException {
    key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
    Session session = (Session) key.attachment();
    session.onWrite();
    //key.interestOps(SelectionKey.OP_READ);
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java

@Override
public void run() {

    while (!isInterrupted()) {

        synchronized (this.pendingConnectionRequests) {

            if (!this.pendingConnectionRequests.isEmpty()) {

                final OutgoingConnection outgoingConnection = this.pendingConnectionRequests.poll();
                try {
                    final SocketChannel socketChannel = SocketChannel.open();
                    socketChannel.configureBlocking(false);
                    final SelectionKey key = socketChannel.register(this.selector, SelectionKey.OP_CONNECT);
                    socketChannel.connect(outgoingConnection.getConnectionAddress());
                    key.attach(outgoingConnection);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportConnectionProblem(ioe);
                        }//from ww  w.j a v a  2  s.  c  om
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.pendingWriteEventSubscribeRequests) {

            if (!this.pendingWriteEventSubscribeRequests.isEmpty()) {
                final SelectionKey oldSelectionKey = this.pendingWriteEventSubscribeRequests.poll();
                final OutgoingConnection outgoingConnection = (OutgoingConnection) oldSelectionKey.attachment();
                final SocketChannel socketChannel = (SocketChannel) oldSelectionKey.channel();

                try {
                    final SelectionKey newSelectionKey = socketChannel.register(this.selector,
                            SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                    newSelectionKey.attach(outgoingConnection);
                    outgoingConnection.setSelectionKey(newSelectionKey);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportTransmissionProblem(ioe);
                        }
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.connectionsToClose) {

            final Iterator<Map.Entry<OutgoingConnection, Long>> closeIt = this.connectionsToClose.entrySet()
                    .iterator();
            final long now = System.currentTimeMillis();
            while (closeIt.hasNext()) {

                final Map.Entry<OutgoingConnection, Long> entry = closeIt.next();
                if ((entry.getValue().longValue() + MIN_IDLE_TIME_BEFORE_CLOSE) < now) {
                    final OutgoingConnection outgoingConnection = entry.getKey();
                    closeIt.remove();
                    // Create new thread to close connection to avoid deadlocks
                    final Runnable closeThread = new Runnable() {

                        @Override
                        public void run() {
                            try {
                                outgoingConnection.closeConnection();
                            } catch (IOException ioe) {
                                outgoingConnection.reportTransmissionProblem(ioe);
                            }
                        }
                    };

                    new Thread(closeThread).start();
                }

            }
        }

        try {
            this.selector.select(10);
        } catch (IOException e) {
            LOG.error(e);
        }

        final Iterator<SelectionKey> iter = this.selector.selectedKeys().iterator();

        while (iter.hasNext()) {
            final SelectionKey key = iter.next();

            iter.remove();
            if (key.isValid()) {
                if (key.isConnectable()) {
                    doConnect(key);
                } else {
                    if (key.isReadable()) {
                        doRead(key);
                        // A read will always result in an exception, so the write key will not be valid anymore
                        continue;
                    }
                    if (key.isWritable()) {
                        doWrite(key);
                    }
                }
            } else {
                LOG.error("Received invalid key: " + key);
            }
        }
    }

    // Finally, try to close the selector
    try {
        this.selector.close();
    } catch (IOException ioe) {
        LOG.debug(StringUtils.stringifyException(ioe));
    }
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java

public void subscribeToWriteEvent(SelectionKey selectionKey) {

    synchronized (this.pendingWriteEventSubscribeRequests) {
        this.pendingWriteEventSubscribeRequests.add(selectionKey);
    }//from   w ww . j a v a2  s.  c om
    synchronized (this.connectionsToClose) {
        this.connectionsToClose.remove((OutgoingConnection) selectionKey.attachment());
    }

}

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

protected void executeIoTasksOnSelectedKeys() {
    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
    while (iterator.hasNext()) {
        SelectionKey selectionKey = iterator.next();
        iterator.remove();//from  w w  w. java  2 s  .  com
        try {
            NioSelectionKeyEntry nioTaskEntry = (NioSelectionKeyEntry) selectionKey.attachment();
            if (nioTaskEntry == null) {
                LOG.error("The nio task is unexpectedly null for selectionKey " + selectionKey);
                return;
            }
            nioTaskEntry.executeTasks(selectionKey);
        } catch (Exception e) {
            LOG.error("Failed to execute the consumer attached to selectionKey " + selectionKey
                    + ".  Cancelling the key and closing the underlying channel", e);
            try {
                selectionKey.channel().close();
            } catch (IOException e1) {
                LOG.error("selection key channel error on close", e);
            }
            selectionKey.cancel();
        }
    }
}

From source file:net.sf.cindy.impl.SimpleEventGenerator.java

private void run() {
    try {/*from  www  .j ava 2  s.  c om*/
        while (!close) {
            beforeSelect(selector);
            if (close)
                break;

            int readyKeyCount = 0;
            try {
                readyKeyCount = selector.select(Constants.CHECK_SESSION_TIMEOUT_INTERVAL);
            } catch (ClosedSelectorException cse) {
                break;
            } catch (IOException e) {
                log.error(e, e);
                break;
            }
            afterSelect(selector);

            if (readyKeyCount > 0) {
                for (Iterator iter = selector.selectedKeys().iterator(); iter.hasNext();) {
                    SelectionKey key = (SelectionKey) iter.next();
                    iter.remove();

                    try {
                        processKey(key);
                    } catch (Exception e) { //Protection catch
                        ((Session) key.attachment()).dispatchException(e);
                    }
                }
            }
        }
    } finally {
        finishedSelect(selector);
    }
}