首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java并发阻塞

Java并发阻塞
EN

Stack Overflow用户
提问于 2022-04-17 04:53:32
回答 1查看 50关注 0票数 0

如果通道未关闭,则会出现阻塞问题,但不能通过关闭来重用该链接。

测试

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2022-04-17 04:54:09

来源

代码语言:javascript
复制
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;
    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71899361

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档