JerseyClient 异步调用似乎留下了挂起的线程

JerseyClient async calls seems to leave hanging threads

我正在使用 jersey-client-3.0-SNAPSHOT。

我会做类似的事情:

 final Client client = createClient();

...

    Builder builder = target.request();
    for (final Entry<String, String> entry : getHeaders().entrySet()) {
        builder = builder.header(entry.getKey(), entry.getValue());
    }
    final Builder finalBuilder = builder;
    executor.submit(() -> {
        final Entity<?> entity = createPostEntity();
        futureResponse = finalBuilder.async().post(entity);
        try {
            response = futureResponse.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
            consumeResponse(response);
        } catch (ExecutionException | TimeoutException | InterruptedException | IOException e) {
            errorConsumer.accept(e);
        }
    });

    if (futureResponse != null) {
        try {
            futureResponse.cancel(true);
        } catch (final Exception e) {
            //does nothing, now we try keep closing resources
        }
    }
    if (response != null) {
        try {
            response.close();
        } catch (final Exception e) {
            //does nothing, now we try keep closing resources
        }
    }

... //等待响应并阅读或其他任何

client.close();

每次创建和销毁其中一个客户端时,都会不断出现一个新线程。

有没有安全的方法来销毁这些线程? 这是预期的行为吗? 我做错了什么吗?

asynchronous 调用 Jersey client 中,每当我们在 client 对象上调用 close() 时,它会破坏 async 中使用的 thread呼唤。因此,预期的行为是每当执行 client.close() 语句时,它都会销毁线程,下一次,将为下一个 async 调用创建一个新线程。

现在,考虑到错误情况,关闭 client 对象和关联线程的安全方法之一如下 -

    Client client = ClientBuilder.newClient();

    WebTarget webTarget = client.target(SERVER_URL).path(API_PATH);

    Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
    // set headers and other stuff

    AsyncInvoker asyncInvoker = invocationBuilder.async();

    asyncInvoker.get(new InvocationCallback<Response>() {

        @Override
        public void completed(Response response) {
            if (response.getStatusInfo().equals(Status.OK)) {
               // parse the response in success scenario
            } else {
               // parse the response if error response is received from server
            }
            client.close();
        }

        @Override
        public void failed(Throwable throwable) {
            System.out.println("An error occurred while calling API");
            throwable.printStackTrace();
            client.close();
        }
    });