1

When using apache htttpasyncclient how does one handle various exception cases properly? Consider the following pseudo code based on this example where I have added the consumer parameter to the execute call. The intention is to make an asynchronous http request where the data is processed as a stream when the bytes come in rather than waiting for the full response to be done before processing. Various issues can occur such as a timeout exception on the http request, failure to connect (could be no network), etc. Is it always guaranteed that for example on a timeout with a response not coming back in time that releaseResources() is always called. The question is where does latch.countDown() need to be put in the below code to always guarantee that the await call doesn't just hang no matter what the exception. Is the call to latch.countDown() in StreamConsumer.releaseResources() enough to prevent hanging on the await?

public static void main(final String[] args) throws Exception {
    client.execute(HttpAsyncMethods.createGet(u), new StreamConsumer(...), new FutureCallback<Boolean>() {
        @Override
        public void cancelled() {
            // Is latch call needed here?
            // latch.countDown();
        }

        @Override
        public void completed(Boolean response) {
            // Is latch call needed here?
            // latch.countDown();
        }

        @Override
        public void failed(Exception e) {
            // Is latch call needed here?
            // latch.countDown();
        }
    });

    latch.await();
}


static class StreamConsumer extends AsyncByteConsumer<Boolean> {
    @Override
    protected void onResponseReceived(final HttpResponse response) {
       latch.countDown();
    }

    @Override
    protected void onByteReceived(final ByteBuffer buf, final IOControl ioctrl) throws IOException {

    }

    @Override
    protected void releaseResources() {
        latch.countDown();
    }

}
user782220
  • 10,677
  • 21
  • 72
  • 135

1 Answers1

0

CloseableHttpAsyncClient#execute method terminates immediately upon submission of a request into the request execution pipeline and returns a Future object representing the future result of the operation.

Therefore the latch in the example is required to make sure that the client does not get shut down immediately after CloseableHttpAsyncClient#execute call.

If one uses CloseableHttpAsyncClient as a singleton with a defined life-cycle (as one should) synchronization of request completion and the client shutdown may be unnecessary.

ok2c
  • 26,450
  • 5
  • 63
  • 71