如何在AsynchronousSocketChannel上正确同步并发读取和写入

时间:2012-09-14 12:17:22

标签: java sockets concurrency nio vert.x

我正在尝试使用CompletionHandler not Futures在vert.x worker Verticle中的AsynchronousSocketChannel上实现单个请求/响应。来自vert.x文档:

  

“工作者Verticle永远不会被多个线程同时执行。”

所以这是我的代码(不确定我的套接字处理100%正确 - 请评论):

    // ommitted: asynchronousSocketChannel.open, connect ...

    eventBus.registerHandler(address, new Handler<Message<JsonObject>>() {
        @Override
        public void handle(final Message<JsonObject> event) {
            final ByteBuffer receivingBuffer = ByteBuffer.allocateDirect(2048);
            final ByteBuffer sendingBuffer = ByteBuffer.wrap("Foo".getBytes());

            asynchronousSocketChannel.write(sendingBuffer, 0L, new CompletionHandler<Integer, Long>() {
                public void completed(final Integer result, final Long attachment) {
                    if (sendingBuffer.hasRemaining()) {
                        long newFilePosition = attachment + result;
                        asynchronousSocketChannel.write(sendingBuffer, newFilePosition, this);
                    }

                    asynchronousSocketChannel.read(receivingBuffer, 0L, new CompletionHandler<Integer, Long>() {
                        CharBuffer charBuffer = null;
                        final Charset charset = Charset.defaultCharset();
                        final CharsetDecoder decoder = charset.newDecoder();

                        public void completed(final Integer result, final Long attachment) {
                            if (result > 0) {
                                long p = attachment + result;
                                asynchronousSocketChannel.read(receivingBuffer, p, this);
                            }

                            receivingBuffer.flip();

                            try {
                                charBuffer = decoder.decode(receivingBuffer);
                                event.reply(charBuffer.toString()); // pseudo code
                            } catch (CharacterCodingException e) { }


                        }

                        public void failed(final Throwable exc, final Long attachment) { }
                    });
                }

                public void failed(final Throwable exc, final Long attachment) { }
            });
        }
    });

我在加载测试期间遇到了很多ReadPendingException和WritePendingException,如果handle方法中一次只有一个线程,这似乎有点奇怪。如果一次只有一个线程使用AsynchronousSocketChannel,那么如何才能完全完成读取或写入?

1 个答案:

答案 0 :(得分:1)

AsynchronousSocketChannel的处理程序在它们自己的AsynchronousChannelGroup上执行,它是ExecutorService的派生物。除非您做出特别的努力,否则处理程序将与启动I / O操作的代码并行执行。

要在Verticle中执行I / O完成处理程序,您必须从该Verticle创建并注册一个处理程序,该处理程序执行AsynchronousSocketChannel的处理程序现在所做的事。

AsynchronousSocketChannel的处理程序应该只在消息中打包它的参数(结果和附件)并将该消息发送到事件总线。