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

rei*_*kje 5 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) { }
            });
        }
    });
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*dov 1

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

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

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