Reputation: 165
I couldn't find any executors that fulfill my requirement. I want to have an ExecutorService with corePoolSize, maximumPoolSize and with BlockingQueue;
When execute function is called, like usual, use core thread, if core threads are in use, then put the task to the queue and if queue is full then create new thread until reaches maximumPoolSize. this is the standard behavior for ThreaPoolExecutor. ThreadPoolExecutor
Everyhing is okey until this part. I can create a ThreadPoolExecutor with this specification.
But for some task, don't queue them create a new thread if core thread is full. But if maximumPoolSize reach then queue the task but put the task first.
How can I implement such a requirement, is there any built-in functionality that I can use.
Upvotes: 0
Views: 298
Reputation: 338516
No, I know of no executor service that prioritizes tasks to be run ahead of other tasks.
But you can effectively do that yourself quite easily. Establish multiple executor services. Use one for the low priority tasks, and another for the high priority tasks.
In the following example, we assume a 12-core machine that is not over-burdened. We assign a thousand tasks to the low priority service. And we assign three tasks to the high priority service. The three important tasks will be scheduled for execution immediately.
ExecutorService highPriorityExecutorService = Executors.newFixedThreadPool( 5 ) ;
ExecutorService lowPriorityExecutorService = Executors.newFixedThreadPool( 3 ) ;
By the way, Project Loom may make moot your issue, if that team succeeds. Performance may be so dramatically improved that in some scenarios your need to prioritize tasks may evaporate.
Project Loom adds virtual threads (a.k.a fibers) to the concurrency facilities of Java. Virtual threads run so cheaply, with more efficient use of memory and CPU, that a common computer may be able to handle millions of threads.
The JVM schedules the many virtual threads onto a few “real” threads managed by the host operating system. Any virtual thread whose work blocks is instantly set aside (“parked”), as another virtual thread is scheduled for immediate execution. The underlying carrier threads, the host OS threads, do not block in such cases. The goal is to keep the host threads constantly working productively whenever any virtual threads are pending.
Experimental builds of OpenJDK with Project Loom technology are available now, based on early-access Java 18.
Upvotes: 1