Denis Savenkov Denis Savenkov - 1 year ago 180
Java Question

How to cancel a particular task by timeout when using ThreadPoolExecutor in Java?

I'm using ThreadPoolExecutor in Java to parallelize items processing. Each item processing is a separate task, that I put it in a queue for the executor to process. Unfortunately, some tasks can take too long and I want to be able to cancel such tasks and continue with the rest. I don't want to wait for shutdown method and its timeout (overall processing takes days).
I want something like looping over currently executed tasks and checking for how long it is running and cancel it if it is above the limit.

Answer Source

This is how you can implement it using Java Concurrency API:

Executor es = Executors.newFixedThreadPool(4);

FutureTask<Void> f = new FutureTask<>(new Callable<Void>(){
    public Void call() throws Exception {
        // do your stuff here
        return null;

try {
    f.get(1, TimeUnit.HOURS);  // define timeout here
} catch (InterruptedException e1) {
    // interrupted
} catch (ExecutionException e1) {
    // execution exception
} catch (TimeoutException e1) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download