Search in sources :

Example 6 with SelectableChannel

use of java.nio.channels.SelectableChannel in project jeromq by zeromq.

the class Poller method run.

@Override
public void run() {
    int returnsImmediately = 0;
    while (!stopping) {
        //  Execute any due timers.
        long timeout = executeTimers();
        while (retired.compareAndSet(true, false)) {
            Iterator<Map.Entry<SelectableChannel, PollSet>> it = fdTable.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<SelectableChannel, PollSet> entry = it.next();
                SelectableChannel ch = entry.getKey();
                PollSet pollset = entry.getValue();
                if (pollset.key == null) {
                    try {
                        pollset.key = ch.register(selector, pollset.ops, pollset.handler);
                    } catch (ClosedChannelException e) {
                    }
                }
                if (pollset.cancelled || !ch.isOpen()) {
                    if (pollset.key != null) {
                        pollset.key.cancel();
                    }
                    it.remove();
                }
            }
        }
        //  Wait for events.
        int rc;
        long start = System.currentTimeMillis();
        try {
            rc = selector.select(timeout);
        } catch (IOException e) {
            throw new ZError.IOException(e);
        }
        if (rc == 0) {
            //  Guess JDK epoll bug
            if (timeout == 0 || System.currentTimeMillis() - start < timeout / 2) {
                returnsImmediately++;
            } else {
                returnsImmediately = 0;
            }
            if (returnsImmediately > 10) {
                rebuildSelector();
                returnsImmediately = 0;
            }
            continue;
        }
        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey key = it.next();
            IPollEvents evt = (IPollEvents) key.attachment();
            it.remove();
            try {
                if (key.isReadable()) {
                    evt.inEvent();
                } else if (key.isAcceptable()) {
                    evt.acceptEvent();
                } else if (key.isConnectable()) {
                    evt.connectEvent();
                }
                if (key.isWritable()) {
                    evt.outEvent();
                }
            } catch (CancelledKeyException e) {
            // channel might have been closed
            }
        }
    }
    stopped = true;
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) SelectionKey(java.nio.channels.SelectionKey) CancelledKeyException(java.nio.channels.CancelledKeyException) IOException(java.io.IOException) SelectableChannel(java.nio.channels.SelectableChannel) Map(java.util.Map) HashMap(java.util.HashMap)

Example 7 with SelectableChannel

use of java.nio.channels.SelectableChannel in project jeromq by zeromq.

the class ZPoller method dispatch.

/**
     * Dispatches the polled events.
     *
     * @param all   the items used for dispatching
     * @param size  the number of items to dispatch
     * @return true if correctly dispatched, false in case of error
     */
protected boolean dispatch(final Collection<ItemHolder> all, int size) {
    ItemHolder[] array = all.toArray(new ItemHolder[all.size()]);
    // protected against handlers unregistering during this loop
    for (ItemHolder holder : array) {
        EventsHandler handler = holder.handler();
        if (handler == null) {
            handler = globalHandler;
        }
        if (handler == null) {
            // no handler, short-circuit
            continue;
        }
        final zmq.PollItem item = holder.item();
        final int events = item.readyOps();
        if (events <= 0) {
            // no events, short-circuit
            continue;
        }
        final Socket socket = holder.socket();
        final SelectableChannel channel = holder.item().getRawSocket();
        if (socket != null) {
            assert (channel == null);
            // dispatch on socket
            if (!handler.events(socket, events)) {
                return false;
            }
        }
        if (channel != null) {
            // dispatch on channel
            assert (socket == null);
            if (!handler.events(channel, events)) {
                return false;
            }
        }
    }
    return true;
}
Also used : SelectableChannel(java.nio.channels.SelectableChannel) Socket(org.zeromq.ZMQ.Socket)

Example 8 with SelectableChannel

use of java.nio.channels.SelectableChannel in project jeromq by zeromq.

the class TestZPoller method testUseNull.

@Test
public void testUseNull() throws IOException {
    ZPoller poller = new ZPoller(new ZStar.VerySimpleSelectorCreator().create());
    SelectableChannel channel = null;
    // ctx.createSocket(ZMQ.SUB);
    Socket socket = null;
    boolean rc = false;
    rc = poller.register(socket, ZPoller.IN);
    Assert.assertFalse("Registering a null socket was successful", rc);
    rc = poller.register(channel, ZPoller.OUT);
    Assert.assertFalse("Registering a null channel was successful", rc);
    int events = poller.poll(10);
    Assert.assertEquals("reading event on without sockets", 0, events);
    rc = poller.isReadable(socket);
    Assert.assertFalse("checking read event on a null socket was successful", rc);
    rc = poller.writable(socket);
    Assert.assertFalse("checking write event on a null socket was successful", rc);
    rc = poller.readable(channel);
    Assert.assertFalse("checking read event on a null channel was successful", rc);
    rc = poller.isWritable(channel);
    Assert.assertFalse("checking write event on a null channel was successful", rc);
    EventsHandler global = null;
    poller.setGlobalHandler(global);
    EventsHandler handler = null;
    rc = poller.register(socket, handler, ZPoller.ERR);
    Assert.assertFalse("Register with handler on a null socket was successful", rc);
    rc = poller.register(channel, ZPoller.ERR);
    Assert.assertFalse("Register with handler on a null channel was successful", rc);
    events = poller.poll(10);
    Assert.assertEquals("reading event with events handlers without sockets", 0, events);
    poller.close();
}
Also used : SelectableChannel(java.nio.channels.SelectableChannel) EventsHandler(org.zeromq.ZPoller.EventsHandler) Socket(org.zeromq.ZMQ.Socket) Test(org.junit.Test)

Example 9 with SelectableChannel

use of java.nio.channels.SelectableChannel in project jdk8u_jdk by JetBrains.

the class WindowsSelectorImpl method implClose.

protected void implClose() throws IOException {
    synchronized (closeLock) {
        if (channelArray != null) {
            if (pollWrapper != null) {
                // prevent further wakeup
                synchronized (interruptLock) {
                    interruptTriggered = true;
                }
                wakeupPipe.sink().close();
                wakeupPipe.source().close();
                for (int i = 1; i < totalChannels; i++) {
                    // Deregister channels
                    if (i % MAX_SELECTABLE_FDS != 0) {
                        // skip wakeupEvent
                        deregister(channelArray[i]);
                        SelectableChannel selch = channelArray[i].channel();
                        if (!selch.isOpen() && !selch.isRegistered())
                            ((SelChImpl) selch).kill();
                    }
                }
                pollWrapper.free();
                pollWrapper = null;
                selectedKeys = null;
                channelArray = null;
                // Make all remaining helper threads exit
                for (SelectThread t : threads) t.makeZombie();
                startLock.startThreads();
            }
        }
    }
}
Also used : SelectableChannel(java.nio.channels.SelectableChannel)

Example 10 with SelectableChannel

use of java.nio.channels.SelectableChannel in project jdk8u_jdk by JetBrains.

the class WindowsSelectorImpl method implDereg.

protected void implDereg(SelectionKeyImpl ski) throws IOException {
    int i = ski.getIndex();
    assert (i >= 0);
    synchronized (closeLock) {
        if (i != totalChannels - 1) {
            // Copy end one over it
            SelectionKeyImpl endChannel = channelArray[totalChannels - 1];
            channelArray[i] = endChannel;
            endChannel.setIndex(i);
            pollWrapper.replaceEntry(pollWrapper, totalChannels - 1, pollWrapper, i);
        }
        ski.setIndex(-1);
    }
    channelArray[totalChannels - 1] = null;
    totalChannels--;
    if (totalChannels != 1 && totalChannels % MAX_SELECTABLE_FDS == 1) {
        totalChannels--;
        // The last thread has become redundant.
        threadsCount--;
    }
    // Remove the key from fdMap, keys and selectedKeys
    fdMap.remove(ski);
    keys.remove(ski);
    selectedKeys.remove(ski);
    deregister(ski);
    SelectableChannel selch = ski.channel();
    if (!selch.isOpen() && !selch.isRegistered())
        ((SelChImpl) selch).kill();
}
Also used : SelectableChannel(java.nio.channels.SelectableChannel)

Aggregations

SelectableChannel (java.nio.channels.SelectableChannel)25 SelectionKey (java.nio.channels.SelectionKey)13 IOException (java.io.IOException)5 Selector (java.nio.channels.Selector)4 SocketChannel (java.nio.channels.SocketChannel)4 Test (org.junit.Test)4 SocketTimeoutException (java.net.SocketTimeoutException)3 CancelledKeyException (java.nio.channels.CancelledKeyException)3 ClosedChannelException (java.nio.channels.ClosedChannelException)3 ServerSocketChannel (java.nio.channels.ServerSocketChannel)3 Socket (org.zeromq.ZMQ.Socket)3 ConnectException (java.net.ConnectException)2 InetSocketAddress (java.net.InetSocketAddress)2 HashMap (java.util.HashMap)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)2 ChannelException (io.netty.channel.ChannelException)1 EventLoopException (io.netty.channel.EventLoopException)1 FileDescriptor (java.io.FileDescriptor)1 Socket (java.net.Socket)1