Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set timeout for task using ThreadPoolTaskExecutor

Is it possible to timeout a task when using ThreadPoolTaskExecutor? I cannot change the ThreadPoolTaskExecutor to ThreadPoolExecutor or to ExecutorService.

like image 702
USer22999299 Avatar asked Dec 12 '16 11:12

USer22999299


People also ask

How do you stop ThreadPoolTaskExecutor?

Look into thread interruption. Thread. stop() it!

What is Queuecapacity in ThreadPoolTaskExecutor?

The default configuration of core pool size is 1, max pool size and queue capacity as 2147483647. This is roughly equivalent to Executors.

What is keep alive time in Threadpoolexecutor?

Returns the thread keep-alive time, which is the amount of time which threads in excess of the core pool size may remain idle before being terminated.

What is core pool size in ThreadPoolTaskExecutor?

The corePoolSize is the minimum number of workers to keep alive without timing out. It is a configurable property of ThreadPoolTaskExecutor. However, the ThreadPoolTaskExecutor abstraction delegates setting this value to the underlying java. util.


2 Answers

After submitting a Callable to your ThreadPoolTaskExecutor you should get a Future. And on this Future, you can call the get(long timeout, TimeUnit unit) function with a TimeUnit, which is the timeout, the maximum time the program will wait until either the future delivers or moves on, by throwing a TimeoutException.

ie (unconfirmed pseudocode)

Future myFuture = threadPoolTaskExecutor.submit(myCallable);
try {
    myResult = myFuture.get(5l,TimeUnit.SECONDS);
} catch(TimeoutException e) {
    // Timeout-Related stuff here
}
like image 55
Scorpio Avatar answered Sep 29 '22 22:09

Scorpio


Refer my below Git hub link for TimeOutThreadPoolTaskExecutor

https://github.com/vivek-gupta-21563/timeoutthreadpool

you can execute or submit a task with preferred time out parameters

execute(() -> System.out.println("Task to execute"), 2, TimeUnit.Minute);

submit(() -> System.out.println("Task to execute"), 2, TimeUnit.Minute);
like image 20
vivek21563 Avatar answered Sep 29 '22 21:09

vivek21563