Java Code Examples for java.nio.channels.SelectionKey#readyOps()

The following examples show how to use java.nio.channels.SelectionKey#readyOps() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NioEventLoop.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
private static void processSelectedKey(SelectionKey k, AbstractNioChannel ch) {
    final NioUnsafe unsafe = ch.unsafe();
    if (!k.isValid()) {
        // close the channel if the key is not valid anymore
        unsafe.close(unsafe.voidPromise());
        return;
    }

    try {
        int readyOps = k.readyOps();
        // Also check for readOps of 0 to workaround possible JDK bug which may otherwise lead
        // to a spin loop
        if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) {
            unsafe.read();
            if (!ch.isOpen()) {
                // Connection already closed - no need to handle write.
                return;
            }
        }
        if ((readyOps & SelectionKey.OP_WRITE) != 0) {
            // Call forceFlush which will also take care of clear the OP_WRITE once there is nothing left to write
            ch.unsafe().forceFlush();
        }
        if ((readyOps & SelectionKey.OP_CONNECT) != 0) {
            // remove OP_CONNECT as otherwise Selector.select(..) will always return without blocking
            // See https://github.com/netty/netty/issues/924
            int ops = k.interestOps();
            ops &= ~SelectionKey.OP_CONNECT;
            k.interestOps(ops);

            unsafe.finishConnect();
        }
    } catch (CancelledKeyException ignored) {
        unsafe.close(unsafe.voidPromise());
    }
}
 
Example 2
Source File: NioProcessor.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void accept(SelectionKey key) {
	NioSession session = (NioSession)key.attachment();
	int ops = key.readyOps();
	if ((ops & SelectionKey.OP_READ) != 0)
		session.read();
	if ((ops & SelectionKey.OP_WRITE) != 0)
		scheduleFlush(session);
}
 
Example 3
Source File: Proxy.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
String printSelectionOps(SelectionKey key) {
    StringBuffer sb=new StringBuffer();
    if ((key.readyOps() & SelectionKey.OP_ACCEPT) !=0)
        sb.append("OP_ACCEPT ");
    if ((key.readyOps() & SelectionKey.OP_CONNECT) !=0)
        sb.append("OP_CONNECT ");
    if ((key.readyOps() & SelectionKey.OP_READ) !=0)
        sb.append("OP_READ ");
    if ((key.readyOps() & SelectionKey.OP_WRITE) !=0)
        sb.append("OP_WRITE ");
    return sb.toString();
}
 
Example 4
Source File: AbstractNioWorker.java    From android-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected void process(Selector selector) throws IOException {
    Set<SelectionKey> selectedKeys = selector.selectedKeys();
    // check if the set is empty and if so just return to not create garbage by
    // creating a new Iterator every time even if there is nothing to process.
    // See https://github.com/netty/netty/issues/597
    if (selectedKeys.isEmpty()) {
        return;
    }
    for (Iterator<SelectionKey> i = selectedKeys.iterator(); i.hasNext();) {
        SelectionKey k = i.next();
        i.remove();
        try {
            int readyOps = k.readyOps();
            if ((readyOps & SelectionKey.OP_READ) != 0 || readyOps == 0) {
                if (!read(k)) {
                    // Connection already closed - no need to handle write.
                    continue;
                }
            }
            if ((readyOps & SelectionKey.OP_WRITE) != 0) {
                writeFromSelectorLoop(k);
            }
        } catch (CancelledKeyException e) {
            close(k);
        }

        if (cleanUpCancelledKeys()) {
            break; // break the loop to avoid ConcurrentModificationException
        }
    }
}
 
Example 5
Source File: NIOReactor.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    final Selector selector = this.selector;
    for (;;) {
        ++reactCount;
        try {
            selector.select(1000L);
            register(selector);
            Set<SelectionKey> keys = selector.selectedKeys();
            try {
                for (SelectionKey key : keys) {
                    Object att = key.attachment();
                    if (att != null && key.isValid()) {
                        int readyOps = key.readyOps();
                        if ((readyOps & SelectionKey.OP_READ) != 0) {
                            read((NIOConnection) att);
                        } else if ((readyOps & SelectionKey.OP_WRITE) != 0) {
                            write((NIOConnection) att);
                        } else {
                            key.cancel();
                        }
                    } else {
                        key.cancel();
                    }
                }
            } finally {
                keys.clear();
            }
        } catch (Throwable e) {
            logger.warn(name, e);
        }
    }
}
 
Example 6
Source File: Proxy.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
String printSelectionOps(SelectionKey key) {
    StringBuffer sb=new StringBuffer();
    if ((key.readyOps() & SelectionKey.OP_ACCEPT) !=0)
        sb.append("OP_ACCEPT ");
    if ((key.readyOps() & SelectionKey.OP_CONNECT) !=0)
        sb.append("OP_CONNECT ");
    if ((key.readyOps() & SelectionKey.OP_READ) !=0)
        sb.append("OP_READ ");
    if ((key.readyOps() & SelectionKey.OP_WRITE) !=0)
        sb.append("OP_WRITE ");
    return sb.toString();
}
 
Example 7
Source File: SocketNioSend.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Selector selector;
    synchronized (Selector.class) {
        // Selector.open() isn't thread safe
        // http://bugs.sun.com/view_bug.do?bug_id=6427854
        // Affects 1.6.0_29, fixed in 1.7.0_01
        selector = Selector.open();
    }
    Member mbr = new MemberImpl("localhost", 9999, 0);
    ChannelData data = new ChannelData();
    data.setOptions(Channel.SEND_OPTIONS_BYTE_MESSAGE);
    data.setAddress(mbr);
    byte[] buf = new byte[8192 * 4];
    data.setMessage(new XByteBuffer(buf,false));
    buf = XByteBuffer.createDataPackage(data);
    int len = buf.length;
    BigDecimal total = new BigDecimal((double)0);
    BigDecimal bytes = new BigDecimal((double)len);
    NioSender sender = new NioSender();
    sender.setDestination(mbr);
    sender.setDirectBuffer(true);
    sender.setSelector(selector);
    sender.setTxBufSize(1024*1024);
    sender.connect();
    sender.setMessage(buf);
    System.out.println("Writing to 9999");
    long start = 0;
    double mb = 0;
    boolean first = true;
    int count = 0;
    DecimalFormat df = new DecimalFormat("##.00");
    while (count<100000) {
        if (first) {
            first = false;
            start = System.currentTimeMillis();
        }
        sender.setMessage(buf);
        int selectedKeys = 0;
        try {
            selectedKeys = selector.select(0);
        } catch (Exception e) {
            e.printStackTrace();
            continue;
        }

        if (selectedKeys == 0) {
            continue;
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey sk = it.next();
            it.remove();
            try {
                int readyOps = sk.readyOps();
                sk.interestOps(sk.interestOps() & ~readyOps);
                if (sender.process(sk, false)) {
                    total = total.add(bytes);
                    sender.reset();
                    sender.setMessage(buf);
                    mb += ( (double) len) / 1024 / 1024;
                    if ( ( (++count) % 10000) == 0) {
                        long time = System.currentTimeMillis();
                        double seconds = ( (double) (time - start)) / 1000;
                        System.out.println("Throughput " + df.format(mb / seconds) + " MB/seconds, total "+mb+" MB, total "+total+" bytes.");
                    }
                }

            } catch (Throwable t) {
                t.printStackTrace();
                return;
            }
        }
        selector.selectedKeys().clear();
    }
    System.out.println("Complete, sleeping 15 seconds");
    Thread.sleep(15000);
}
 
Example 8
Source File: SocketNioValidateSend.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Selector selector;
    synchronized (Selector.class) {
        // Selector.open() isn't thread safe
        // http://bugs.sun.com/view_bug.do?bug_id=6427854
        // Affects 1.6.0_29, fixed in 1.7.0_01
        selector = Selector.open();
    }
    Member mbr = new MemberImpl("localhost", 9999, 0);
    byte seq = 0;
    byte[] buf = new byte[50000];
    Arrays.fill(buf,seq);
    int len = buf.length;
    BigDecimal total = new BigDecimal((double)0);
    BigDecimal bytes = new BigDecimal((double)len);
    NioSender sender = new NioSender();
    sender.setDestination(mbr);
    sender.setDirectBuffer(true);
    sender.setSelector(selector);
    sender.connect();
    sender.setMessage(buf);
    System.out.println("Writing to 9999");
    long start = 0;
    double mb = 0;
    boolean first = true;
    int count = 0;

    DecimalFormat df = new DecimalFormat("##.00");
    while (count<100000) {
        if (first) {
            first = false;
            start = System.currentTimeMillis();
        }
        sender.setMessage(buf);
        int selectedKeys = 0;
        try {
            selectedKeys = selector.select(0);
        } catch (Exception e) {
            e.printStackTrace();
            continue;
        }

        if (selectedKeys == 0) {
            continue;
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey sk = it.next();
            it.remove();
            try {
                int readyOps = sk.readyOps();
                sk.interestOps(sk.interestOps() & ~readyOps);
                if (sender.process(sk, false)) {
                    total = total.add(bytes);
                    sender.reset();
                    seq++;
                    Arrays.fill(buf,seq);
                    sender.setMessage(buf);
                    mb += ( (double) len) / 1024 / 1024;
                    if ( ( (++count) % 10000) == 0) {
                        long time = System.currentTimeMillis();
                        double seconds = ( (double) (time - start)) / 1000;
                        System.out.println("Throughput " + df.format(mb / seconds) + " MB/seconds, total "+mb+" MB, total "+total+" bytes.");
                    }
                }

            } catch (Throwable t) {
                t.printStackTrace();
                return;
            }
        }
    }
    System.out.println("Complete, sleeping 15 seconds");
    Thread.sleep(15000);
}
 
Example 9
Source File: LotsOfCancels.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
Example 10
Source File: NioSender.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * State machine to send data
 * @param key SelectionKey
 * @return boolean
 * @throws IOException
 */
public boolean process(SelectionKey key, boolean waitForAck) throws IOException {
    int ops = key.readyOps();
    key.interestOps(key.interestOps() & ~ops);
    //in case disconnect has been called
    if ((!isConnected()) && (!connecting)) throw new IOException("Sender has been disconnected, can't selection key.");
    if ( !key.isValid() ) throw new IOException("Key is not valid, it must have been cancelled.");
    if ( key.isConnectable() ) {
        if ( socketChannel.finishConnect() ) {
            completeConnect();
            if ( current != null ) key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
            return false;
        } else  {
            //wait for the connection to finish
            key.interestOps(key.interestOps() | SelectionKey.OP_CONNECT);
            return false;
        }//end if
    } else if ( key.isWritable() ) {
        boolean writecomplete = write(key);
        if ( writecomplete ) {
            //we are completed, should we read an ack?
            if ( waitForAck ) {
                //register to read the ack
                key.interestOps(key.interestOps() | SelectionKey.OP_READ);
            } else {
                //if not, we are ready, setMessage will reregister us for another write interest
                //do a health check, we have no way of verify a disconnected
                //socket since we don't register for OP_READ on waitForAck=false
                read(key);//this causes overhead
                setRequestCount(getRequestCount()+1);
                return true;
            }
        } else {
            //we are not complete, lets write some more
            key.interestOps(key.interestOps()|SelectionKey.OP_WRITE);
        }//end if
    } else if ( key.isReadable() ) {
        boolean readcomplete = read(key);
        if ( readcomplete ) {
            setRequestCount(getRequestCount()+1);
            return true;
        } else {
            key.interestOps(key.interestOps() | SelectionKey.OP_READ);
        }//end if
    } else {
        //unknown state, should never happen
        log.warn("Data is in unknown state. readyOps="+ops);
        throw new IOException("Data is in unknown state. readyOps="+ops);
    }//end if
    return false;
}
 
Example 11
Source File: SocketNioValidateSend.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Selector selector;
    synchronized (Selector.class) {
        // Selector.open() isn't thread safe
        // http://bugs.sun.com/view_bug.do?bug_id=6427854
        // Affects 1.6.0_29, fixed in 1.7.0_01
        selector = Selector.open();
    }
    Member mbr = new MemberImpl("localhost", 9999, 0);
    byte seq = 0;
    byte[] buf = new byte[50000];
    Arrays.fill(buf,seq);
    int len = buf.length;
    BigDecimal total = new BigDecimal((double)0);
    BigDecimal bytes = new BigDecimal((double)len);
    NioSender sender = new NioSender();
    sender.setDestination(mbr);
    sender.setDirectBuffer(true);
    sender.setSelector(selector);
    sender.connect();
    sender.setMessage(buf);
    System.out.println("Writing to 9999");
    long start = 0;
    double mb = 0;
    boolean first = true;
    int count = 0;

    DecimalFormat df = new DecimalFormat("##.00");
    while (count<100000) {
        if (first) {
            first = false;
            start = System.currentTimeMillis();
        }
        sender.setMessage(buf);
        int selectedKeys = 0;
        try {
            selectedKeys = selector.select(0);
        } catch (Exception e) {
            e.printStackTrace();
            continue;
        }

        if (selectedKeys == 0) {
            continue;
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey sk = it.next();
            it.remove();
            try {
                int readyOps = sk.readyOps();
                sk.interestOps(sk.interestOps() & ~readyOps);
                if (sender.process(sk, false)) {
                    total = total.add(bytes);
                    sender.reset();
                    seq++;
                    Arrays.fill(buf,seq);
                    sender.setMessage(buf);
                    mb += ( (double) len) / 1024 / 1024;
                    if ( ( (++count) % 10000) == 0) {
                        long time = System.currentTimeMillis();
                        double seconds = ( (double) (time - start)) / 1000;
                        System.out.println("Throughput " + df.format(mb / seconds) + " MB/seconds, total "+mb+" MB, total "+total+" bytes.");
                    }
                }

            } catch (Throwable t) {
                t.printStackTrace();
                return;
            }
        }
    }
    System.out.println("Complete, sleeping 15 seconds");
    Thread.sleep(15000);
}
 
Example 12
Source File: LotsOfCancels.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
Example 13
Source File: NioSenderTest.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
public void run() {
    while (true) {

        int selectedKeys = 0;
        try {
            selectedKeys = selector.select(100);
            //               if ( selectedKeys == 0 ) {
            //                   System.out.println("No registered interests. Sleeping for a second.");
            //                   Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
            continue;
        }

        if (selectedKeys == 0) {
            continue;
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey sk = it.next();
            it.remove();
            try {
                int readyOps = sk.readyOps();
                sk.interestOps(sk.interestOps() & ~readyOps);
                NioSender sender = (NioSender) sk.attachment();
                if ( sender.process(sk, (testOptions&Channel.SEND_OPTIONS_USE_ACK)==Channel.SEND_OPTIONS_USE_ACK) ) {
                    System.out.println("Message completed for handler:"+sender);
                    Thread.sleep(2000);
                    sender.reset();
                    sender.setMessage(XByteBuffer.createDataPackage(getMessage(mbr)));
                }


            } catch (Throwable t) {
                t.printStackTrace();
                return;
            }
        }
    }
}
 
Example 14
Source File: LotsOfCancels.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
Example 15
Source File: NioSender.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * State machine to send data
 * @param key SelectionKey
 * @return boolean
 * @throws IOException
 */
public boolean process(SelectionKey key, boolean waitForAck) throws IOException {
    int ops = key.readyOps();
    key.interestOps(key.interestOps() & ~ops);
    //in case disconnect has been called
    if ((!isConnected()) && (!connecting)) throw new IOException("Sender has been disconnected, can't selection key.");
    if ( !key.isValid() ) throw new IOException("Key is not valid, it must have been cancelled.");
    if ( key.isConnectable() ) {
        if ( socketChannel.finishConnect() ) {
            completeConnect();
            if ( current != null ) key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
            return false;
        } else  {
            //wait for the connection to finish
            key.interestOps(key.interestOps() | SelectionKey.OP_CONNECT);
            return false;
        }//end if
    } else if ( key.isWritable() ) {
        boolean writecomplete = write(key);
        if ( writecomplete ) {
            //we are completed, should we read an ack?
            if ( waitForAck ) {
                //register to read the ack
                key.interestOps(key.interestOps() | SelectionKey.OP_READ);
            } else {
                //if not, we are ready, setMessage will reregister us for another write interest
                //do a health check, we have no way of verify a disconnected
                //socket since we don't register for OP_READ on waitForAck=false
                read(key);//this causes overhead
                setRequestCount(getRequestCount()+1);
                return true;
            }
        } else {
            //we are not complete, lets write some more
            key.interestOps(key.interestOps()|SelectionKey.OP_WRITE);
        }//end if
    } else if ( key.isReadable() ) {
        boolean readcomplete = read(key);
        if ( readcomplete ) {
            setRequestCount(getRequestCount()+1);
            return true;
        } else {
            key.interestOps(key.interestOps() | SelectionKey.OP_READ);
        }//end if
    } else {
        //unknown state, should never happen
        log.warn("Data is in unknown state. readyOps="+ops);
        throw new IOException("Data is in unknown state. readyOps="+ops);
    }//end if
    return false;
}
 
Example 16
Source File: NioSenderTest.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
public void run() {
    while (true) {

        int selectedKeys = 0;
        try {
            selectedKeys = selector.select(100);
            //               if ( selectedKeys == 0 ) {
            //                   System.out.println("No registered interests. Sleeping for a second.");
            //                   Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
            continue;
        }

        if (selectedKeys == 0) {
            continue;
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey sk = it.next();
            it.remove();
            try {
                int readyOps = sk.readyOps();
                sk.interestOps(sk.interestOps() & ~readyOps);
                NioSender sender = (NioSender) sk.attachment();
                if ( sender.process(sk, (testOptions&Channel.SEND_OPTIONS_USE_ACK)==Channel.SEND_OPTIONS_USE_ACK) ) {
                    System.out.println("Message completed for handler:"+sender);
                    Thread.sleep(2000);
                    sender.reset();
                    sender.setMessage(XByteBuffer.createDataPackage(getMessage(mbr)));
                }


            } catch (Throwable t) {
                t.printStackTrace();
                return;
            }
        }
    }
}
 
Example 17
Source File: LotsOfCancels.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
Example 18
Source File: LotsOfCancels.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
Example 19
Source File: SocketNioSend.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Selector selector = Selector.open();
    Member mbr = new MemberImpl("localhost", 9999, 0);
    ChannelData data = new ChannelData();
    data.setOptions(Channel.SEND_OPTIONS_BYTE_MESSAGE);
    data.setAddress(mbr);
    byte[] buf = new byte[8192 * 4];
    data.setMessage(new XByteBuffer(buf,false));
    buf = XByteBuffer.createDataPackage(data);
    int len = buf.length;
    BigDecimal total = new BigDecimal((double)0);
    BigDecimal bytes = new BigDecimal((double)len);
    NioSender sender = new NioSender();
    sender.setDestination(mbr);
    sender.setDirectBuffer(true);
    sender.setSelector(selector);
    sender.setTxBufSize(1024*1024);
    sender.connect();
    sender.setMessage(buf);
    System.out.println("Writing to 9999");
    long start = 0;
    double mb = 0;
    boolean first = true;
    int count = 0;
    DecimalFormat df = new DecimalFormat("##.00");
    while (count<100000) {
        if (first) {
            first = false;
            start = System.currentTimeMillis();
        }
        sender.setMessage(buf);
        int selectedKeys = 0;
        try {
            selectedKeys = selector.select(0);
        } catch (Exception e) {
            e.printStackTrace();
            continue;
        }

        if (selectedKeys == 0) {
            continue;
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey sk = it.next();
            it.remove();
            try {
                int readyOps = sk.readyOps();
                sk.interestOps(sk.interestOps() & ~readyOps);
                if (sender.process(sk, false)) {
                    total = total.add(bytes);
                    sender.reset();
                    sender.setMessage(buf);
                    mb += ( (double) len) / 1024 / 1024;
                    if ( ( (++count) % 10000) == 0) {
                        long time = System.currentTimeMillis();
                        double seconds = ( (double) (time - start)) / 1000;
                        System.out.println("Throughput " + df.format(mb / seconds) + " MB/seconds, total "+mb+" MB, total "+total+" bytes.");
                    }
                }

            } catch (Throwable t) {
                t.printStackTrace();
                return;
            }
        }
        selector.selectedKeys().clear();
    }
    System.out.println("Complete, sleeping 15 seconds");
    Thread.sleep(15000);
}
 
Example 20
Source File: NioSender.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * State machine to send data.
 * @param key The key to use
 * @param waitForAck Wait for an ack
 * @return <code>true</code> if the processing was successful
 * @throws IOException An IO error occurred
 */
public boolean process(SelectionKey key, boolean waitForAck) throws IOException {
    int ops = key.readyOps();
    key.interestOps(key.interestOps() & ~ops);
    //in case disconnect has been called
    if ((!isConnected()) && (!connecting)) throw new IOException(sm.getString("nioSender.sender.disconnected"));
    if ( !key.isValid() ) throw new IOException(sm.getString("nioSender.key.inValid"));
    if ( key.isConnectable() ) {
        if ( socketChannel.finishConnect() ) {
            completeConnect();
            if ( current != null ) key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
            return false;
        } else  {
            //wait for the connection to finish
            key.interestOps(key.interestOps() | SelectionKey.OP_CONNECT);
            return false;
        }//end if
    } else if ( key.isWritable() ) {
        boolean writecomplete = write();
        if ( writecomplete ) {
            //we are completed, should we read an ack?
            if ( waitForAck ) {
                //register to read the ack
                key.interestOps(key.interestOps() | SelectionKey.OP_READ);
            } else {
                //if not, we are ready, setMessage will reregister us for another write interest
                //do a health check, we have no way of verify a disconnected
                //socket since we don't register for OP_READ on waitForAck=false
                read();//this causes overhead
                setRequestCount(getRequestCount()+1);
                return true;
            }
        } else {
            //we are not complete, lets write some more
            key.interestOps(key.interestOps()|SelectionKey.OP_WRITE);
        }//end if
    } else if ( key.isReadable() ) {
        boolean readcomplete = read();
        if ( readcomplete ) {
            setRequestCount(getRequestCount()+1);
            return true;
        } else {
            key.interestOps(key.interestOps() | SelectionKey.OP_READ);
        }//end if
    } else {
        //unknown state, should never happen
        log.warn(sm.getString("nioSender.unknown.state", Integer.toString(ops)));
        throw new IOException(sm.getString("nioSender.unknown.state", Integer.toString(ops)));
    }//end if
    return false;
}