Bai Shen
Bai Shen

Reputation: 21

How to limit a task from using all threads in a thread pool?

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

Answers (2)

Andrey Vityuk
Andrey Vityuk

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

Vladimir Dyuzhev
Vladimir Dyuzhev

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

Related Questions