【发布时间】:2014-01-08 17:00:16
【问题描述】:
我有一个通过 Apache 库发出 http 请求的 Callable。但是,如果请求花费的时间太长,我想杀死线程。为此,我可以中断 Callable,但我需要捕获 InterruptedException 以阻止自己。我该怎么做?
private final class HelloWorker implements Callable<String> {
private String url;
public HelloWorker(String url) {
this.url = url;
}
public CloseableHttpResponse call() throws Exception {
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(getCustomSslConnectionSocketFactory())
.build();
return httpClient.execute(new HttpGet(url));
}
}
private CloseableResponse getHttpResponse(String url) {
ExecutorService executorService = Executors.newFixedThreadPool(threadPoolSize);
Future<String> future = executorService.submit(new HelloWorker());
try {
// try to get a response within 5 seconds
return future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
// kill the thread
future.cancel(true);
}
return null;
}
注意future.cancel(true) 不会杀死线程,因为它所做的只是中断线程,而我的代码没有捕获 InterruptedException。但是,由于httpClient.execute 阻塞,我无法弄清楚如何执行此操作,并且我无法将工作分成块。
在调用 httpClient.execute() 时捕获 InterruptedException 就足够了吗?
public CloseableHttpResponse call() throws Exception {
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(getCustomSslConnectionSocketFactory())
.build();
try {
return httpClient.execute(new HttpGet(url));
} catch (InterruptedException) {
return null;
}
}
【问题讨论】:
-
a
Future将捕获您未捕获的每个Throwable。.get()如果你需要它会给你。 -
"但是,如果请求时间过长,我想杀死线程"。不,你没有。你想设置一个超时。
-
如果对您有帮助,记得接受。
标签: java multithreading apache threadpool interrupt