avalon
avalon

Reputation: 2291

Java Executors cancel job by timeout with inner executor

I have a big thread pool like

ThreadPoolExecutor pool = new ThreadPoolExecutor(cores, 50, 30L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3000));

I want to submit a task there. But I don't want to call future.get() at all, I want to submit it and forget.

But, I want my task to be cancelled in a certain time period. So I do the following:

public void run(){

FutureTask<WorkerWrapper> task = new FutureTask<>(()->worker.process(tmpArg));
executor.execute(task);
res=task.get(2, TimeUnit.MINUTES);
executor.shutdown();    

}

In other words, I call executor inside executor. Is it safe and stable? Or can I cancel my task by timeout other way?

Upvotes: 2

Views: 115

Answers (2)

John Vint
John Vint

Reputation: 40256

The only real way to achieve this, AFAIK, is to have a second ScheduledExecutor. You'd still need a handle of the Future but only pass it to the scheduled executor for cancellation.

Future<WorkedWrapper> task = executor.execute(() -> worker.process(tmpArg));
scheduledExecutor.schedule(() -> task.cancel(true), 2, TimeUnit.MINUTES);

There may be a more fluent way of handling this with CompleteableFutures but I am not 100% sure of that.

Upvotes: 1

Steve B.
Steve B.

Reputation: 57294

ScheduledThreadPoolExecutor has a method that allows to to schedule a runnable and get a future back. You can combine this with the timed get on the future:

ScheduedThreadPoolExecutor e = ...
Future<T> f = e.submit(new Runnable(){..},new T(){});
Object ignore = f.get(timeout, timeunit);

Upvotes: 0

Related Questions