ExecutorService that interrupts tasks after a timeout

后端 未结 9 2384
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 16:19

I\'m looking for an ExecutorService implementation that can be provided with a timeout. Tasks that are submitted to the ExecutorService are interrupted if they take longer t

9条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 16:39

    After ton of time to survey,
    Finally, I use invokeAll method of ExecutorService to solve this problem.
    That will strictly interrupt the task while task running.
    Here is example

    ExecutorService executorService = Executors.newCachedThreadPool();
    
    try {
        List> callables = new ArrayList<>();
        // Add your long time task (callable)
        callables.add(new VaryLongTimeTask());
        // Assign tasks for specific execution timeout (e.g. 2 sec)
        List> futures = executorService.invokeAll(callables, 2000, TimeUnit.MILLISECONDS);
        for (Future future : futures) {
            // Getting result
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    
    executorService.shutdown();
    
    
    

    The pro is you can also submit ListenableFuture at the same ExecutorService.
    Just slightly change the first line of code.

    ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    

    ListeningExecutorService is the Listening feature of ExecutorService at google guava project (com.google.guava) )

    提交回复
    热议问题