JerseyClient异步调用似乎会导致线程挂起 [英] JerseyClient async calls seems to leave hanging threads
问题描述
我正在使用jersey-client-3.0-SNAPSHOT.
I'm using 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
}
}
...//等待响应并阅读或其他内容
... //wait for responses and read or whatever
client.close();
每次创建和销毁其中一个客户端时,都会不断出现新线程.
And a new thread keeps appearing each time a create and destroy one of those clients.
有销毁那些线程的安全方法吗? 这是预期的行为吗? 做错什么了吗?
Is there a safe way on destroying those threads? Is this an expected behaviour? Am a doing anything wrong?
推荐答案
在Jersey client
中的asynchronous
调用中,每当我们在client
对象上调用close()
时,它都会破坏async
中使用的thread
打电话.因此,预期的行为是,每当执行client.close()
语句时,它将破坏线程,并在下一次为下一个async
调用创建新线程.
In asynchronous
calls in Jersey client
, whenever we call close()
on client
object, it destroys the thread
used in async
calling. So, it is expected behavior that whenever client.close()
statement will get executed, it will destroy the thread and next time, a new thread will get created for next async
call.
现在,考虑到错误情况,关闭client
对象和关联线程的安全方法之一是-
Now, one of the safe way to close client
object and associated thread considering error scenario is below -
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();
}
});
这篇关于JerseyClient异步调用似乎会导致线程挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!