Search in sources :

Example 56 with SelectionKey

use of java.nio.channels.SelectionKey in project openhab1-addons by openhab.

the class ConnectionManager method run.

/**
     * Main method of the thread.
     * Establishes new connections and waits for input data.
     */
@Override
public void run() {
    final Object sync = new Object();
    long lastCloseDetectTime = System.nanoTime();
    while (!this.threadTreminate) {
        long currTime = System.nanoTime();
        try {
            int timeoutMSec = DETECT_CLOSED_CHANNELS_INTERVAL_MSEC - (int) ((currTime - lastCloseDetectTime) / 1000000L);
            if (timeoutMSec <= 0 || this.selector.select(timeoutMSec) == 0) {
                // Detect closed channels
                synchronized (sync) {
                    this.callback.runOnRefreshThreadAsync(new LcnBindingNotification() {

                        @Override
                        public void execute() {
                            for (Connection conn : ConnectionManager.this.connectionsById.values()) {
                                if (!conn.isChannelConnected() && !conn.isChannelConnecting()) {
                                    logger.warn(String.format("Channel \"%s\" was closed unexpectedly (reconnecting...).", conn.getSets().getId()));
                                    conn.beginReconnect(RECONNECT_INTERVAL_MSEC);
                                }
                            }
                            synchronized (sync) {
                                sync.notify();
                            }
                        }
                    });
                    sync.wait();
                }
                lastCloseDetectTime = currTime;
            } else {
                // Process selected keys (connect or read events)
                Iterator<SelectionKey> iter = this.selector.selectedKeys().iterator();
                while (iter.hasNext()) {
                    final SelectionKey key = iter.next();
                    // The invocation is done sync. to keep the SelectionKey valid
                    synchronized (sync) {
                        this.callback.runOnRefreshThreadAsync(new LcnBindingNotification() {

                            @Override
                            public void execute() {
                                Connection conn = (Connection) key.attachment();
                                try {
                                    if (key.isConnectable()) {
                                        conn.finishConnect();
                                    } else if (key.isReadable()) {
                                        conn.readAndProcess();
                                    }
                                } catch (IOException ex) {
                                    logger.warn(String.format("Cannot process channel \"%s\" (reconnecting...): %s", conn.getSets().getId(), ex.getMessage()));
                                    conn.beginReconnect(RECONNECT_INTERVAL_MSEC);
                                }
                                synchronized (sync) {
                                    sync.notify();
                                }
                            }
                        });
                        sync.wait();
                    }
                    iter.remove();
                }
            }
            synchronized (this.channelRegisterSync) {
            }
        // Force a wait here if a new channel is registering
        } catch (InterruptedException ex) {
        } catch (IOException ex) {
            logger.error("Selection failure: " + ex.getMessage());
        }
    }
}
Also used : LcnBindingNotification(org.openhab.binding.lcn.common.LcnBindingNotification) SelectionKey(java.nio.channels.SelectionKey) IOException(java.io.IOException)

Example 57 with SelectionKey

use of java.nio.channels.SelectionKey in project XobotOS by xamarin.

the class SelectorImpl method doCancel.

/**
     * Removes cancelled keys from the key set and selected key set, and
     * deregisters the corresponding channels. Returns the number of keys
     * removed from the selected key set.
     */
private int doCancel() {
    int deselected = 0;
    Set<SelectionKey> cancelledKeys = cancelledKeys();
    synchronized (cancelledKeys) {
        if (cancelledKeys.size() > 0) {
            for (SelectionKey currentKey : cancelledKeys) {
                mutableKeys.remove(currentKey);
                deregister((AbstractSelectionKey) currentKey);
                if (mutableSelectedKeys.remove(currentKey)) {
                    deselected++;
                }
            }
            cancelledKeys.clear();
        }
    }
    return deselected;
}
Also used : AbstractSelectionKey(java.nio.channels.spi.AbstractSelectionKey) SelectionKey(java.nio.channels.SelectionKey)

Example 58 with SelectionKey

use of java.nio.channels.SelectionKey in project voltdb by VoltDB.

the class VoltNetwork method registerChannel.

/**
     * Register a channel with the selector and create a Connection that will pass incoming events
     * to the provided handler.
     * @param channel
     * @param handler
     * @throws IOException
     */
Connection registerChannel(final SocketChannel channel, final InputHandler handler, final int interestOps, final ReverseDNSPolicy dns, final CipherExecutor cipherService, final SSLEngine sslEngine) throws IOException {
    synchronized (channel.blockingLock()) {
        channel.configureBlocking(false);
        channel.socket().setKeepAlive(true);
    }
    Callable<Connection> registerTask = new Callable<Connection>() {

        @Override
        public Connection call() throws Exception {
            final VoltPort port = VoltPortFactory.createVoltPort(channel, VoltNetwork.this, handler, (InetSocketAddress) channel.socket().getRemoteSocketAddress(), m_pool, cipherService, sslEngine);
            port.registering();
            /*
                 * This means we are used by a client. No need to wait then, trigger
                 * the reverse DNS lookup now.
                 */
            if (dns != ReverseDNSPolicy.NONE) {
                port.resolveHostname(dns == ReverseDNSPolicy.SYNCHRONOUS);
            }
            try {
                SelectionKey key = channel.register(m_selector, interestOps, null);
                port.setKey(key);
                port.registered();
                //Fix a bug witnessed on the mini where the registration lock and the selector wakeup contained
                //within was not enough to prevent the selector from returning the port after it was registered,
                //but before setKey was called. Suspect a bug in the selector.wakeup() or register() implementation
                //on the mac.
                //The null check in invokeCallbacks will catch the null attachment, continue, and do the work
                //next time through the selection loop
                key.attach(port);
                return port;
            } finally {
                m_ports.add(port);
                m_numPorts.incrementAndGet();
            }
        }
    };
    FutureTask<Connection> ft = new FutureTask<Connection>(registerTask);
    m_tasks.offer(ft);
    m_selector.wakeup();
    try {
        return ft.get();
    } catch (Exception e) {
        throw new IOException(e);
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) FutureTask(java.util.concurrent.FutureTask) IOException(java.io.IOException) Callable(java.util.concurrent.Callable) AsynchronousCloseException(java.nio.channels.AsynchronousCloseException) CancelledKeyException(java.nio.channels.CancelledKeyException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException)

Example 59 with SelectionKey

use of java.nio.channels.SelectionKey in project voltdb by VoltDB.

the class SocketJoiner method runPrimary.

/*
     * After startup everything is a primary and can accept
     * new nodes into the cluster. This loop accepts the new socket
     * and passes it off the HostMessenger via the JoinHandler interface
     */
private void runPrimary() throws Exception {
    try {
        // start the server socket on the right interface
        doBind();
        while (true) {
            try {
                final int selectedKeyCount = m_selector.select();
                if (selectedKeyCount == 0)
                    continue;
                Set<SelectionKey> selectedKeys = m_selector.selectedKeys();
                try {
                    for (SelectionKey key : selectedKeys) {
                        processSSC((ServerSocketChannel) key.channel());
                    }
                } finally {
                    selectedKeys.clear();
                }
            } catch (ClosedByInterruptException e) {
                throw new InterruptedException();
            } catch (ClosedSelectorException e) {
                throw new InterruptedException();
            } catch (Exception e) {
                LOG.error("fault occurrent in the connection accept loop", e);
            }
        }
    } finally {
        for (ServerSocketChannel ssc : m_listenerSockets) {
            try {
                ssc.close();
            } catch (IOException e) {
            }
        }
        m_listenerSockets.clear();
        try {
            m_selector.close();
        } catch (IOException e) {
        }
        m_selector = null;
    }
}
Also used : ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) SelectionKey(java.nio.channels.SelectionKey) IOException(java.io.IOException) IOException(java.io.IOException) EOFException(java.io.EOFException) JSONException(org.json_voltpatches.JSONException) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) ClosedSelectorException(java.nio.channels.ClosedSelectorException) ServerSocketChannel(java.nio.channels.ServerSocketChannel) ClosedSelectorException(java.nio.channels.ClosedSelectorException)

Example 60 with SelectionKey

use of java.nio.channels.SelectionKey in project voltdb by VoltDB.

the class VoltNetwork method resumeSelection.

private void resumeSelection(VoltPort port) {
    SelectionKey key = port.getKey();
    if (key.isValid()) {
        key.interestOps(port.interestOps());
    } else {
        m_ports.remove(port);
        m_numPorts.decrementAndGet();
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey)

Aggregations

SelectionKey (java.nio.channels.SelectionKey)202 IOException (java.io.IOException)93 SocketChannel (java.nio.channels.SocketChannel)59 Selector (java.nio.channels.Selector)44 ServerSocketChannel (java.nio.channels.ServerSocketChannel)41 ClosedChannelException (java.nio.channels.ClosedChannelException)30 InetSocketAddress (java.net.InetSocketAddress)27 CancelledKeyException (java.nio.channels.CancelledKeyException)25 ByteBuffer (java.nio.ByteBuffer)24 ClosedSelectorException (java.nio.channels.ClosedSelectorException)17 SelectableChannel (java.nio.channels.SelectableChannel)13 Test (org.junit.Test)13 Iterator (java.util.Iterator)9 Socket (java.net.Socket)7 ArrayList (java.util.ArrayList)7 SocketTimeoutException (java.net.SocketTimeoutException)6 AbstractSelectionKey (java.nio.channels.spi.AbstractSelectionKey)6 EOFException (java.io.EOFException)5 DatagramChannel (java.nio.channels.DatagramChannel)5 HashSet (java.util.HashSet)5