[concurrency-interest] ThreadPoolTask

Jean Morissette jean.morissette at gmail.com
Sat Jul 8 14:00:31 EDT 2006


Hi,

I need to create a pool of threads that run only one thead-safe task
forever.  The task, which is a Runnable, must be passed in the
constructor.  Also, the thread pool size should be resizable and have
some lifecycling capabilities.

I was thinking to create it on top of ThreadPoolExecutor, by setting
corePoolSize to zero and by using a custom queue that is always full
of the same task instance. So, by adjusting maxPoolSize, we can set
the number of threads executing the task. Here are some code to show
what I mean.

public class ThreadPoolTask {

	private ThreadPoolExecutor executor;

	public ThreadPoolTask(Runnable task) {
		this.executor = new ThreadPoolExecutor(0, 1, 1, TimeUnit.SECONDS,
new FullQueue(task));
	}

	public void setPoolSize(int size) {
		executor.setMaximumPoolSize(size);
	}

	public int getPoolSize() {
		return executor.getMaximumPoolSize();
	}

	private static class FullQueue implements BlockingQueue {
		// ...
	}
}

What do you think?  Is there a more elegant way to implement my requirements?

Thanks,
Jean


More information about the Concurrency-interest mailing list