'got 'CancellationException: Request execution cancelled' always when throwing an exception in httpasyncclient callback

I use HttpAysnClient to do http requests, and I found when I throw an exception in the failed callback, the next request always be failed, how to fix it?

I use maven dependency: 'org.apache.httpcomponents:httpasyncclient:4.1.5'.

my java test code:


CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();

try {

    httpclient.start();

    AtomicBoolean fireException = new AtomicBoolean(false);

    while (true) {

        try {

            String url;

            if (fireException.compareAndSet(false, true)) {

                url = "http://localhost:8080"; // throw Connection refused

            } else {

                url = "http://www.apache.org/";

            }

            final HttpGet request2 = new HttpGet(url);

            httpclient.execute(request2, new FutureCallback<HttpResponse>() {

                public void completed(final HttpResponse response2) {

                    System.out.println("completed, " + request2.getRequestLine() + "->" + response2.getStatusLine());

                }

                public void failed(final Exception ex) {

                    System.out.println("failed, " + request2.getRequestLine() + "->" + ex);

                    throw new RuntimeException();

                }

                public void cancelled() {

                    System.out.println(request2.getRequestLine() + " cancelled");

                }

            });

            TimeUnit.SECONDS.sleep(1);

        } catch (Exception e) {

            e.printStackTrace();

            TimeUnit.SECONDS.sleep(1);

        }

    }

} finally {

    httpclient.close();

}

exception in the next requests: java.util.concurrent.CancellationException: Request execution cancelled



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source