Search in sources :

Example 26 with Selector

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

the class CommUp method doClient.

void doClient(SocketAddress peerAddress) {
    SctpChannel sc = null;
    try {
        debug("connecting to " + peerAddress);
        sc = SctpChannel.open();
        sc.configureBlocking(false);
        check(sc.isBlocking() == false, "Should be in non-blocking mode");
        sc.connect(peerAddress);
        Selector selector = Selector.open();
        SelectionKey selectiontKey = sc.register(selector, OP_CONNECT);
        /* Expect two interest Ops */
        boolean opConnectReceived = false;
        boolean opReadReceived = false;
        for (int z = 0; z < 2; z++) {
            debug("select " + z);
            int keysAdded = selector.select(TIMEOUT);
            debug("returned " + keysAdded + " keys");
            if (keysAdded > 0) {
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> i = keys.iterator();
                while (i.hasNext()) {
                    SelectionKey sk = i.next();
                    i.remove();
                    SctpChannel readyChannel = (SctpChannel) sk.channel();
                    /* OP_CONNECT */
                    if (sk.isConnectable()) {
                        /* some trivial checks */
                        check(opConnectReceived == false, "should only received one OP_CONNECT");
                        check(opReadReceived == false, "should not receive OP_READ before OP_CONNECT");
                        check(readyChannel.equals(sc), "channels should be equal");
                        check(!sk.isAcceptable(), "key should not be acceptable");
                        check(!sk.isReadable(), "key should not be readable");
                        check(!sk.isWritable(), "key should not be writable");
                        /* now process the OP_CONNECT */
                        opConnectReceived = true;
                        check((sk.interestOps() & OP_CONNECT) == OP_CONNECT, "selection key interest ops should contain OP_CONNECT");
                        sk.interestOps(OP_READ);
                        check((sk.interestOps() & OP_CONNECT) != OP_CONNECT, "selection key interest ops should not contain OP_CONNECT");
                        check(sc.finishConnect(), "finishConnect should return true");
                    } else /* OP_READ */
                    if (sk.isReadable()) {
                        /* some trivial checks */
                        check(opConnectReceived == true, "should receive one OP_CONNECT before OP_READ");
                        check(opReadReceived == false, "should not receive OP_READ before OP_CONNECT");
                        check(readyChannel.equals(sc), "channels should be equal");
                        check(!sk.isAcceptable(), "key should not be acceptable");
                        check(sk.isReadable(), "key should be readable");
                        check(!sk.isWritable(), "key should not be writable");
                        check(!sk.isConnectable(), "key should not be connectable");
                        /* now process the OP_READ */
                        opReadReceived = true;
                        selectiontKey.cancel();
                        /* try with small buffer to see if native
                             * implementation can handle this */
                        ByteBuffer buffer = ByteBuffer.allocateDirect(1);
                        readyChannel.receive(buffer, null, clientHandler);
                        check(clientHandler.receivedCommUp(), "Client should have received COMM_UP");
                        /* dont close (or put anything on) the channel until
                             * we check that the server's accepted channel also
                             * received COMM_UP */
                        serverHandler.waitForCommUp();
                    } else {
                        fail("Unexpected selection key");
                    }
                }
            } else {
                fail("Client selector returned 0 ready keys");
                /* stop the server */
                server.thread().interrupt();
            }
        }
    //for
    } catch (IOException ioe) {
        unexpected(ioe);
    } catch (InterruptedException ie) {
        unexpected(ie);
    }
}
Also used : SctpChannel(com.sun.nio.sctp.SctpChannel) SelectionKey(java.nio.channels.SelectionKey) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Selector(java.nio.channels.Selector)

Example 27 with Selector

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

the class WakeupSpeed method main.

public static void main(String[] argv) throws Exception {
    int waitTime = 4000;
    Selector selector = Selector.open();
    try {
        selector.wakeup();
        long t1 = System.currentTimeMillis();
        selector.select(waitTime);
        long t2 = System.currentTimeMillis();
        long totalTime = t2 - t1;
        if (totalTime > waitTime)
            throw new RuntimeException("Test failed");
    } finally {
        selector.close();
    }
}
Also used : Selector(java.nio.channels.Selector)

Example 28 with Selector

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

the class RacyDeregister method main.

public static void main(String[] args) throws Exception {
    InetAddress addr = InetAddress.getByName(null);
    ServerSocketChannel sc = ServerSocketChannel.open();
    sc.socket().bind(new InetSocketAddress(addr, 0));
    SocketChannel.open(new InetSocketAddress(addr, sc.socket().getLocalPort()));
    SocketChannel accepted = sc.accept();
    accepted.configureBlocking(false);
    SocketChannel.open(new InetSocketAddress(addr, sc.socket().getLocalPort()));
    SocketChannel accepted2 = sc.accept();
    accepted2.configureBlocking(false);
    final Selector sel = Selector.open();
    SelectionKey key2 = accepted2.register(sel, SelectionKey.OP_READ);
    final SelectionKey[] key = new SelectionKey[] { accepted.register(sel, SelectionKey.OP_READ) };
    // thread that will be changing key[0].interestOps to OP_READ | OP_WRITE
    new Thread() {

        public void run() {
            try {
                for (int k = 0; k < 15; k++) {
                    for (int i = 0; i < 10000; i++) {
                        synchronized (notifyLock) {
                            synchronized (selectorLock) {
                                sel.wakeup();
                                key[0].interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                            }
                            notified = false;
                            long beginTime = System.currentTimeMillis();
                            while (true) {
                                notifyLock.wait(5000);
                                if (notified) {
                                    break;
                                }
                                long endTime = System.currentTimeMillis();
                                if (endTime - beginTime > 5000) {
                                    succTermination = false;
                                    // wake up main thread doing select()
                                    sel.wakeup();
                                    return;
                                }
                            }
                        }
                    }
                }
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            } catch (Exception e) {
                System.out.println(e);
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            }
        }
    }.start();
    // main thread will be doing registering/deregistering with the sel
    while (true) {
        sel.select();
        if (Boolean.TRUE.equals(succTermination)) {
            System.out.println("Test passed");
            sel.close();
            sc.close();
            break;
        } else if (Boolean.FALSE.equals(succTermination)) {
            System.out.println("Failed to pass the test");
            sel.close();
            sc.close();
            throw new RuntimeException("Failed to pass the test");
        }
        synchronized (selectorLock) {
        }
        if (sel.selectedKeys().contains(key[0]) && key[0].isWritable()) {
            synchronized (notifyLock) {
                notified = true;
                notifyLock.notify();
                key[0].cancel();
                sel.selectNow();
                key2 = accepted2.register(sel, SelectionKey.OP_READ);
                key[0] = accepted.register(sel, SelectionKey.OP_READ);
            }
        }
        key2.cancel();
        sel.selectedKeys().clear();
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SelectionKey(java.nio.channels.SelectionKey) InetSocketAddress(java.net.InetSocketAddress) InetAddress(java.net.InetAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Selector(java.nio.channels.Selector)

Example 29 with Selector

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

the class ReadAfterConnect method main.

public static void main(String[] argv) throws Exception {
    try (ByteServer server = new ByteServer();
        SocketChannel sc = SocketChannel.open(server.address())) {
        server.acceptConnection();
        try (Selector sel = Selector.open()) {
            sc.configureBlocking(false);
            sc.register(sel, SelectionKey.OP_READ);
            // Previously channel would get selected here, although there is nothing to read
            if (sel.selectNow() != 0)
                throw new Exception("Select returned nonzero value");
        }
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) Selector(java.nio.channels.Selector)

Example 30 with Selector

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

the class SelectAfterRead method main.

public static void main(String[] argv) throws Exception {
    // server: accept connection and write one byte
    try (ByteServer server = new ByteServer();
        SocketChannel sc = SocketChannel.open(server.address())) {
        server.acceptConnection();
        server.write(1);
        try (Selector sel = Selector.open()) {
            sc.read(ByteBuffer.allocate(1));
            sc.configureBlocking(false);
            sc.register(sel, SelectionKey.OP_READ);
            // nothing to read
            if (sel.selectNow() != 0)
                throw new Exception("Select returned nonzero value");
        }
    }
    // server: accept connection and write two bytes
    try (ByteServer server = new ByteServer();
        SocketChannel sc = SocketChannel.open(server.address())) {
        server.acceptConnection();
        server.write(2);
        try (Selector sel = Selector.open()) {
            sc.configureBlocking(false);
            sc.register(sel, SelectionKey.OP_READ);
            if (sel.select(TIMEOUT) != 1)
                throw new Exception("One selected key expected");
            sel.selectedKeys().clear();
            // previously on Windows a channel would get selected only once
            if (sel.selectNow() != 1)
                throw new Exception("One selected key expected");
            // read in the channel
            if (sc.read(ByteBuffer.allocate(1)) != 1)
                throw new Exception("One byte expected");
            if (sc.read(ByteBuffer.allocate(1)) != 1)
                throw new Exception("One byte expected");
            if (sel.selectNow() != 0)
                throw new Exception("Select returned nonzero value");
        }
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) Selector(java.nio.channels.Selector)

Aggregations

Selector (java.nio.channels.Selector)186 SelectionKey (java.nio.channels.SelectionKey)84 IOException (java.io.IOException)70 SocketChannel (java.nio.channels.SocketChannel)51 InetSocketAddress (java.net.InetSocketAddress)38 ByteBuffer (java.nio.ByteBuffer)28 ServerSocketChannel (java.nio.channels.ServerSocketChannel)27 Test (org.junit.Test)14 DatagramChannel (java.nio.channels.DatagramChannel)13 ClosedChannelException (java.nio.channels.ClosedChannelException)12 CancelledKeyException (java.nio.channels.CancelledKeyException)11 NioEndpoint (org.apache.tomcat.util.net.NioEndpoint)10 ClosedSelectorException (java.nio.channels.ClosedSelectorException)9 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)8 EOFException (java.io.EOFException)7 ServerSocket (java.net.ServerSocket)7 SelectableChannel (java.nio.channels.SelectableChannel)7 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)5 Iterator (java.util.Iterator)5 MemberImpl (org.apache.catalina.tribes.membership.MemberImpl)5