Reputation: 21
I'm using a thread pool to execute tasks in the background of my application. However, some of my tasks are heavier than others. So I'd like to limit the heavy tasks to a certain subset of the thread pool, thereby leaving at least a few threads open for any lightweight tasks to execute.
Is there a simple way to do this?
Upvotes: 2
Views: 178
Reputation: 1019
The most simple way is to use separate thread pools for different "tasks weight".
Even you can create separate class which exposes separate methods for differents tasks.
Upvotes: 1
Reputation: 18336
As it was said, the cleanest way is to use a separate thread pool for heavy threads.
Another way is to use a Semaphore. Create a semaphore with a count of, for example, three. Heavy threads have to acquire() it first. Only three heavy ones would be able to do so. The rest will wait (or fail, if you use tryAcquire()).
Of course, the thread needs to "know" it is a "heavy" one. For third-party threads it doesn't work, so see "two pools" approach again. :-)
Upvotes: 0