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

标签 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");
      }
    }

最佳答案

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

在这里,您将了解如何为 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...");
    }
}

关于java - 有没有办法让线程池线程退出处理给定的任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49348694/

相关文章:

multithreading - JVM线程与tomcat线程有何不同,它们是否有一个映射到内核线程的公共(public)池

c++ - 为什么 std::future::wait_for 的行为不如预期?

c++ - 将 future 与Boost线程池一起使用

typescript - 类图中的 Promise

java - 启动我的 java.exe 在哪里?

在 C 中的 for 循环中创建多个 pthread

java - Java 的最佳配置文件

在一个线程上创建的 C# 控件不能作为另一线程上控件的父级

java - 如何在 java 中使用 bouncycaSTLe 将 PrivateKeyUsage 扩展添加到证书?

java - 共享首选项会导致应用程序崩溃。安卓工作室