Prioritizing tasks workaround with ScheduledExecutorService

The idea is inspired from https://stackoverflow.com/a/22668079/285571

There is situations when you need to have possibility to set priority of execution for tasks that have scheduled in ScheduledExecutorService.

PriorityBlockingQueue can help with ordering of tasks by priority. Elements can be ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.

Unfortunately ScheduledExecutorService has no possibility to set PriorityBlockingQueue as the core queue for tasks.

As workaround we can combine ScheduledExecutorService and ThreadPoolExecutor to achieve execution of scheduled tasks depending on priority.

Here the code of tasks manager:

As you can see we use single threaded ScheduledExecutorService for scheduling tasks. When tasks is fired it submited in the ThreadPoolExecutor witch has constructed with PriorityBlockingQueue used for ordering tasks by priority.

Here is how the PrioritizedTask looks like:

It implements Comparable interface for proper ordering in PriorityBlockingQueue. Also this class implemented with supporting FIFO logic.

This workaround not highly strict in execution of scheduled tasks. This means that task with same delay(eg 2 seconds) will be executed with ignoring priority in case when at least one thread of ThreadPoolExecutor is free.

So this workaround will work, when you have count of tasks bigger then count of threads. Each thread that becomes free will start execute task with highest priority.

Full code available on GitHub https://github.com/Hronom/prioritized-scheduling-example