Today I had another time the problem to execute many short tasks in a thread pooled environment. One way could be to write the pooling itselfs (like the other times in history ;)). But I thought: Why to reinvent the wheel every time and not using standardized libraries like the java.util.concurrent.*?
What I want:
- A self enlarging and shrinking ThreadPool depending on the queued tasks. (Because sometimes it is nothing to do and sometimes it could be to get many hundreds of tasks in a short time)
- A definable Limit of maximum running Threads (Because we cannot create hundreds of threads just for this task. Keep in mind: the tasks have a short run time)
- Queuing the Tasks to run later, if the ThreadPool has reached the given limits
So I looked at the given Examples and the Executors-Class, which provides fast and simple methods:
- newCachedThreadPool : This looks good, but unfortunately you can’t define a maximum limit of threads.
- newFixedThreadPool : This handles the wanted limitation, but not the automatic enlarging and shrinking.
So we cannot use the predefined methods and need to instantiate ThreadPoolExecutor directly.