0

I have several tasks that are being created by some event. I want to execute the last few tasks(suppose 6) always.

I am using a fixed thread pool. But the problem I am facing is that, it uses a blocking queue internally. I want to dequeue the tasks from the blocking queue if there are new tasks coming in, without pushing them to the executor. How can I achieve this? Is there a different approach to this problem?

ralph
  • 153
  • 2
  • 9
  • Duplicate of [Java Executors: how can I set task priority?](http://stackoverflow.com/questions/3198660/java-executors-how-can-i-set-task-priority) - Set a higher priority on the new tasks and the executor will run those first. You'll need to define what attribute/s to use as a priority. – Augusto Feb 15 '15 at 08:40
  • 1
    @Augusto I also want to remove the old tasks with low priority. – ralph Feb 15 '15 at 08:44

1 Answers1

0

In order to do what you want, you can use a ScheduledThreadPoolExecutor. And set the flag setRemoveOnCancelPolicy(true).

This executor returns a Future when you call the submit methods. These futures have a cancel() method that you can call when the new request comes in. You can even cancel the tasks that are currently running if you want too.

There's another alternative to call ThreadPoolExecutor.getQueue().clear(), but this is not safe! So please don't try it :)

Augusto
  • 28,839
  • 5
  • 58
  • 88