Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove old queued tasks in ThreadPoolExecutor and insert new tasks instead?

I load a lot of images form internet with a ThreadPoolExecutor.

When new images found, I need to render it first, in that case I want to abandon the old tasks which are still queued in the ThreadPoolExecutor and added these new items to download.

I found there are no "clear queue" method in ThreadPoolExecutor, and "purge" method sounds like not good for this.

What should I do?

I just thought to call "shutdown" of this executor and recreate a new one to do this, not sure whether it is appropriate.

like image 789
virsir Avatar asked Oct 24 '10 12:10

virsir


People also ask

How do you clear ThreadPoolExecutor?

Java ThreadPoolExecutor remove() MethodThe remove() method of ThreadPoolExecutor class removes this task from the executor's internal queue if it is present, thus causing it not to be run if it has not already started.

Can I reuse ExecutorService after shutdown?

After calling shutdown on a ExecutorService, no new Task will be accepted. This means you have to create a new ExecutorService for each round of tasks.

How do I reuse ExecutorService?

You can reuse the executor service if you restructure your code somewhat. Basically you collect all your tasks, execute them, and await execution before proceeding. Of course, you could also alternatively just use a new Executor Service for each of your time steps, but at least you have options.

Which method can cancel the future task triggered by submit () of ExecutorService?

Two different methods are provided for shutting down an ExecutorService . The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks.


1 Answers

Have you tried this?

ThreadPoolExecutor pool = .....;  pool.remove(task);

task is the Runnable you want to remove.

or if you want to clear the queue.

pool.getQueue().clear() 
like image 66
punkers Avatar answered Sep 20 '22 11:09

punkers