Is there a possibility to set priority to tasks which are executed by Executors? I've found some statements in JCIP about it's possible but I cannot find any example and I cannot find anything related in docs.
From JCIP:
An execution policy specifies the "what, where, when, and how" of task execution, including:
- ...
- In what order should tasks be executed (FIFO, LIFO, priority order)?
- ...
UPD: I realized that I asked not exactly what I wanted to ask. What I really wanted is:
How to use/emulate setting threads priority (i.e. what was thread.setPriority()
) with executors framework?
you can use ThreadPoolExecutor with Priority blocking queue How to implement PriorityBlockingQueue with ThreadPoolExecutor and custom tasks
The idea here is to use a PriorityBlockingQueue in the executor. For this:
First you need to hold priority on your future:
Next you need to define comparator that would correctly sort the priority futures:
Next let's assume we have a lengthy job like this:
Then in order to execute these jobs in priority the code will look like:
This is a lot of code but that's nearly the only way this can be accomplished.
On my machine the output is like the following:
You can specify a
ThreadFactory
in theThreadPoolExecutor
constructor (orExecutors
factory method). This allows you to provide threads of a given thread priority for the executor.To get different thread priorities for different jobs, you'd need to send them to executors with different thread factories.
You can implement your own ThreadFactory and set it within ThreadPoolExecutor like this:
where my OpJobThreadFactory looks like the following:
Please be aware that setPriority(..) normally does not work under Linux. See the following links for the full details:
Currently the only concrete implementations of the Executor interface are the ThreadPoolExecutor and the ScheduledThreadpoolExecutor
Instead of using the utility / factory class Executors, you should create an instance using a constructor.
You can pass a BlockingQueue to the constructors of the ThreadPoolExecutor.
One of the implementations of the BlockingQueue, the PriorityBlockingQueue lets you pass a Comparator to a constructor, that way enabling you to decide the order of execution.