有没有办法让线程池线程退出处理给定的任务?

时间:2018-03-18 13:59:07

标签: java multithreading future executorservice threadpoolexecutor

我有一个场景,其中来自执行程序线程池的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");
      }
    }

1 个答案:

答案 0 :(得分:2)

我认为您的问题是管理对产品服务的请求。如果为每个请求正确配置读取超时,则不必担心中断任务执行。

在这里,您将了解如何为WebServiceTemplateRestTemplate设置读取超时:

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...");
    }
}
相关问题