How to correctly synchronize simultaneous reads and writes in AsynchronousSocketChannel

I am trying to implement a single request / response on an AsynchronousSocketChannel at a vertical vertical top vert.x using CompletionHandler not Futures. From the vert.x documentation:

"Workers' peaks are never executed simultaneously by more than one thread."

So, here is my code (not sure if I got the socket processing 100% correct - comment):

    // 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) { }
            });
        }
    });

I experience a lot of ReadPendingException and WritePendingException errors during load testing, which seems a little strange if there is only one thread at a time in the descriptor method. How can it be that reading or writing is not completely completed if only one thread works with AsynchronousSocketChannel at a time?

+5
1

AsynchronousSocketChannel AsynchronousChannelGroup, ExecutorService. , , -.

- , , AsynchronousSocketChannel.

AsynchronousSocketChannel ( ) .

+1

All Articles