我有一个场景,其中执行程序线程池中的 n 个线程调用不同的 Web 服务,但所有线程都应在指定的时间限制内完成其任务,否则所有池线程应退出处理其任务并返回到其执行程序池。
我编写的代码运行良好,但唯一困扰我的情况是我无法取消已经启动的任务,即等待外部 Web 服务响应的线程。
我知道 future.cancel(true) 无法帮助我实现这一目标,但是有什么方法可以实现我想要的目标吗?
我不能用池线程无限期地等待 Web 服务响应。提前致谢!
public class CallProductServiceTask implements Callable<Object>{
public Object call(){
// Call to product service
// For SOAP Client
ProductRequest productRequest = new ProductRequest("prodId");
ProductResponse response = (ProductResponse)webServiceTemplate.marshalSendAndReceive(productRequest);
// For REST Client
ResponseEntity<ProductResponse> response = restTemplate.exchange(productResourceUrl, HttpMethod.POST, productRequest, ProductResponse.class);
}
}
class Test{
ExecutorService executor = Executors.newFixedThreadPool(2);
public static void main(String args[]){
Future ft = executor.submit(new CallProductServiceTask());
try{
Object result = ft.get(3, TimeUnit.SECONDS);
} catch (TimeoutException e) {
boolean c = future.cancel(true);
System.out.println("Timeout " + c);
} catch (InterruptedException | ExecutionException e) {
System.out.println("interrupted");
}
System.out.println("END");
}
}
最佳答案
我认为您的问题是管理对产品服务的请求。如果为每个请求正确配置读取超时,您就不必担心中断任务执行。
在这里,您将了解如何为 WebServiceTemplate
和 RestTemplate
设置读取超时:
How to set read timeout in WebServiceTemplate
?
How to set read timeout in RestTemplate
?
我将为基于 RestTemplate
的方法编写一些伪代码。 (我不记得 WebServiceTemplate
抛出了什么异常。尽管如此,想法仍然是一样的。)
CallProductServiceTask#call
:
try {
final ResponseEntity<?> response = restTemplate.exchange(...);
return parseResponse(response);
} catch (RestClientException e) {
final Throwable cause = e.getCause();
if (cause != null && cause instanceof SocketTimeoutException) {
throw new BusinessLogicException(cause);
}
}
Test.main
:
try {
future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
final Throwable cause = e.getCause();
if (cause != null && cause instanceof BusinessLogicException) {
System.out.println("The task was interrupted...");
}
}
关于java - 有没有办法让线程池线程退出处理给定的任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49348694/