gpt4 book ai didi

java - Jersey 客户端异步调用似乎留下了挂起的线程

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:11:27 26 4
gpt4 key购买 nike

我正在使用 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();

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

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

最佳答案

Jersey client 中的 asynchronous 调用中,每当我们在 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();
}
});

关于java - Jersey 客户端异步调用似乎留下了挂起的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44329063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com