ThreadPoolExecutor and Pool Sizes Quirk
I recently ran into a problem while using ThreadPoolExecutor. As you probably know, ThreadPoolExecutor takes (among the others), two parameters - corePoolSize and maximumPoolSize. Also by default (and in Java5 you can't change the default) it never stops threads from the "core" pool.
So I've tried to set corePoolSize quite low and raise maximumPoolSize. After some checks I could see that my pool does not behave as expected - I've got very long queue and only core pool threads started. After going deeper into the documentation I've found this:
If there are more than corePoolSize but less than maximumPoolSize threads running, a new thread will be created only if the queue is full.And I've used unbounded queue. So, basically, with unbounded queue one should never make maximumPoolSize larger then corePoolSize (at least this won't make any impact - no more then core pool threads will be created).
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)





Comments
Liam Knox replied on Mon, 2010/11/01 - 6:32am
Jess Holle replied on Mon, 2010/11/01 - 10:20am
Yes, the documented behavior is rather frustrating and should be just an option (and not the default one...)
I griped about this on another forum and got the following response:
Oleksandr Alesinskyy replied on Wed, 2010/11/03 - 5:44pm
Liam Knox replied on Wed, 2010/11/03 - 6:19pm
in response to:
Jess Holle
Vitalii Tymchyshyn replied on Fri, 2010/11/05 - 8:12am
in response to:
Oleksandr Alesinskyy
Here is workaround I use:
new RejectedExecutionHandler() { public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { try { executor.getQueue().put(r); } catch (InterruptedException e) { throw new RuntimeException(e); } } }Pass this to ThreadPoolExecutor executor constructor and you will get flow control.P.S. Of course you will need a bounded queue for RejectedExecutionHandler to be used
County Line Nissan replied on Mon, 2011/08/01 - 10:35am