Java AIO concurrent blocking

101 Views Asked by At

If the channel is not closed, there will be a blocking problem, but the link cannot be reused by closing

test

C:\Users\hxm>ab -k -c100 -n1000 http://127.0.0.1:8080/
This is ApacheBench, Version 2.3 <$Revision: 1843412 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 (be patient)
Completed 100 requests
apr_pollset_poll: The timeout specified has expired (70007)
Total of 100 requests completed
1

There are 1 best solutions below

1
On

source

public class HSocket implements Runnable {

    private Integer port = 8080;

    private static final Logger LOGGER = Logger.getLogger(HSocket.class.getName());

    private AsynchronousServerSocketChannel ssc;

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    public void run() {
        try {
            AsynchronousChannelGroup cg = AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(8));
            ssc = AsynchronousServerSocketChannel.open(cg);
            ssc.bind(new InetSocketAddress(port), 100);
            ssc.accept(this, new CompletionHandler<AsynchronousSocketChannel, HSocket>() {
                @Override
                public void completed(AsynchronousSocketChannel channel, HSocket attachment) {
                    try {
                        ssc.accept(attachment, this);
                    } finally {
                        String body = generateErrorResponse("<h1>aaa</h1>");
                        channel.write(ByteBuffer.wrap(body.getBytes()));
                    }
                }

                @Override
                public void failed(Throwable exc, HSocket attachment) {
                    ssc.accept(attachment, this);
                }
            });
            LOGGER.log(Level.INFO, "server port " + port);
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        new Thread(new HSocket()).start();
    }

    private String generateErrorResponse(String message) {
        return "HTTP/1.1 200 OK\r\n" +
                "Content-type:text/html\r\n" +
                "Connection:keep-alive\r\n" +
                "Content-Length:" + message.length() + "\r\n" +
                "\r\n" +
                message;
    }

}