I have an ExecutorService
that I submit tasks to:
private final ExecutorService CUSTOM_POOL = Executors
.newCachedThreadPool();
private Queue<Future<?>> customTasksHandles;
private boolean started;
private Runnable task = new Runnable() {
@Override
public void run() {
if (!started) {return;}
...
customTasksHandles.add(CUSTOM_POOL.submit(new CustomTask(customData)));
...
}
}
I need to create public void stop()
and public void start()
functions. The stop()
function would future.cancel()
for every task that has been submitted to the executor, while the start()
would start running the task
Runnable
again.
public void stop() {
...
Future customTasksHandle= customTasksHandles.poll();
while (customTasksHandle!=null) {
customTasksHandle.cancel(true);
customTasksHandle=locationTasksHandles.poll();
}
...
started = false;
}
public void start() {started = true;}
I tried to just CUSTOM_POOL.shutdown()
, however it seems to make it impossible to submit new tasks later, after the start()
is called. It seems that the only way is to loop over all submitted tasks and call .cancel()
on each.
However, how do I get all submitted tasks without adding each task to a list/queue when submitting? Is there a better way to do it other than the way above? I was hoping for a List<Future> submittedTasks = CUSTOM_POOL.getAllSubmittedTasks()
method of sorts, but there doesn't seem to be one. Interestingly, .shutdown()
and invoke()
methods do return List<Future>
, but have side-effects.