[concurrency-interest] Thread Pools

Joe Bowbeer joe.bowbeer at gmail.com
Fri Jul 21 15:54:12 EDT 2006


On 7/21/06, Patrick Eger <peger at automotive.com> wrote:
>
> Hi, I know this has come up again and again, (I think I brought it up once
> or twice ;-) But are there any plans to add a "preferExistingThreads()" to
> the ThreadPoolExecutor, to address the issue of dynamic pool sizing, or is
> there any way I can extend these classes to do such?
>
> IE I would like a:
>
> 1) potentially infinite queue of tasks (currently using a
> LinkedBlockingQueue)
>
> 2) executed by up to MAX threads concurrently
>
> 3) which go away after a period of inactivity, allowing the pool to shrink
> to MIN (or zero) size
>
> 4) preferring to use already existing threads rather than creating new ones
>
> This is currently impossible with the current setup AFAICS; I have continued
> to have to use my own thread pools because of this, though I would love to
> switch to the standard JUC classes. #3 was covered in JDK 6 with the
> capability to allow core threads to timeout, but I cannot find a way to make
> #4 possible with current JUC. The existing behaviour will always end up
> creating CORE threads even though they are unnecessary to execute existing
> work.
>
> Thanks in advance for any replies.
>

To recap, the problem you're trying to overcome is that TPE prefers
(1) to create a core thread, (2) queue task, (3) create additional
thread.

In other words, MAX_THREADS is effectively ignored if queue is unbounded:

    ExecutorService newEgerThreadPool() {
        return new ThreadPoolExecutor(0, MAX_THREADS,
                                      60L, TimeUnit.SECONDS,
                                      new LinkedQueue<Runnable>());
    }

So you're requesting an option to switch priority of 2 and 3.

I can't address that but I do see a new allowCoreThreadTimeOut method
in the pipeline that might have the same effect:

http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/
  => java/util/concurrent/ThreadPoolExecutor.java

pool.allowCoreThreadTimeOut(true) can be used to apply the time-out
policy to core threads as well, so long as the keepAliveTime value is
non-zero.

I think this might work:

    ExecutorService newEgerThreadPool() {
        ThreadPoolExecutor pool =
            new ThreadPoolExecutor(MAX_THREADS, MAX_THREADS,
                                      60L, TimeUnit.SECONDS,
                                      new LinkedQueue<Runnable>());
        pool.allowCoreThreadTimeOut(true);
        return pool;
    }

--Joe


More information about the Concurrency-interest mailing list