2

I have written an NIO.2 http client. When reading the response, it is possible that the full response hasn't been received so as soon as I get the content-length header on the byte buffer I know how much is left so I use that or read until the completion handler tells me i got 0 bytes back. Simplifying the problem I am using a CompletionHandler

public void completed(Integer result, ClientSession clientSession) {
    final ByteBuffer buffer = clientSession.getBuffer();
    final ResponseParser responseParser = clientSession.getResponseParser();

    buffer.flip();
    if (responseParser.parse(buffer)) {
        final HttpResponse httpResponse = responseParser.httpResponse();
        doStuff(httpResponse);    
        buffer.clear();
    } else {
        clientSession.getChannel().read(buffer, clientSession, this);
    }
}

If the response read is incomplete, the read on the channel will come back to the same completionhandler and the process will recurse until done. The completion handler shown is specified in the preceeding http request write e.g

clientSession.getChannel().write(buffer, clientSession, new ReadHandler())

All works great until I ramp up the load and I get a ReadPendingException. It was my understanding that this should not happen, as long as no more than 1 read/write is executed in a completionhandler. What is my mistake?

paulturnip
  • 106
  • 5

1 Answers1

0

You must implement a queue of buffer and wait for a read to complete. If the queue is not empty you take buffer with poll(). You must define a flag (busy) to monitor state of read operation. Probably you must implement also a queue of clientSession correlated to buffer element. Do same thing for write operation.

    private Queue<ByteBuffer> input = new LinkedList<>();
                    ...
                    try {
                           
                            clientSession.getChannel().read(buffer, clientSession, this);

                        }catch(ReadPendingException ex) {

                            input.add(buffer);
                            busy= true;

                        }

                     ...
Bored
  • 499
  • 4
  • 11