net.spy.concurrent
Class ThreadPool

java.lang.Object
  extended by java.util.concurrent.AbstractExecutorService
      extended by java.util.concurrent.ThreadPoolExecutor
          extended by net.spy.concurrent.ThreadPool
All Implemented Interfaces:
Executor, ExecutorService

public class ThreadPool
extends ThreadPoolExecutor

A producer/consumer thread pool for easy parallelism.

Quick start example (assuming you want to do a million tasks, 15 at time):

 // Get a thread pool that will perform 15 tasks at a time
 ThreadPool tp=new ThreadPool("Test Pool", 15);
 // Start the thread pool
 tp.start();

 // Do the tasks in a loop, throttling to make sure all we don't
 // create too many objects that aren't ready to be used.
 for(int i=0; i<1000000; i++) {
     // Don't have more than 32 unclaimed tasks
     tp.waitForTaskCount(32);
     tp.addTask(new MyRunnableClass());
 }
 tp.waitForCompletion();
 
 

The ThreadPoolManager instance is responsible for sizing and resizing the pool. On start(), the ThreadPoolManager will size the pool to the start size configured in the ThreadPool. The manager will receive a notification after any task is added to the pool and may choose to take action at that point. Otherwise, it will sleep for a certain amount of time (one minute by default) and then begin its main loop verifying the number of idle threads satisfies the configuration.

If the number of idle threads is too low, it will create as many as is required to have the appropriate number of idle threads as long as the total number of threads will not exceed the configured maximum.

If the number of idle threads is too high, it will reduce the total number of threads by one (for each loop).


Nested Class Summary
 
Nested classes/interfaces inherited from class java.util.concurrent.ThreadPoolExecutor
ThreadPoolExecutor.AbortPolicy, ThreadPoolExecutor.CallerRunsPolicy, ThreadPoolExecutor.DiscardOldestPolicy, ThreadPoolExecutor.DiscardPolicy
 
Constructor Summary
ThreadPool(String name)
          Get an instance of ThreadPool with five threads and a normal priority.
ThreadPool(String name, int n)
          Get an instance of ThreadPool.
ThreadPool(String name, int n, int max)
          Get an instance of ThreadPool.
ThreadPool(String name, int n, int max, int prio)
          Get an instance of ThreadPool.
ThreadPool(String name, int n, int max, int prio, BlockingQueue<Runnable> q)
          Get an instance of ThreadPool.
ThreadPool(String name, int n, int max, int prio, int size)
          Get an instance of ThreadPool.
 
Method Summary
 void addTask(Runnable r)
          Add a task for one of the threads to execute.
 boolean addTask(Runnable r, long timeout)
          Add a task for one of the threads to execute.
protected  void afterExecute(Runnable r, Throwable t)
           
protected  void beforeExecute(Thread t, Runnable r)
           
 int getIdleThreadCount()
          Find out how many threads are idle.
 int getMinTotalThreads()
          Get the minimum number of threads that may exist in the thread pool at any moment.
 ThreadPoolObserver getMonitor()
          Get the monitor that receives notifications when a worker thread finishes a job.
 int getPriority()
          Get the priority that will be used for any new threads within this thread group.
 void setMonitor(ThreadPoolObserver m)
          Set the observer who will receive notification whenever a task is completed.
 void setPriority(int p)
          Set the priority to be used for any new threads within this threaad group.
 void start()
          Start the ThreadPool.
 String toString()
          String me.
 void waitForCompletion()
          Shut down all of the threads after all jobs are complete, and wait for all tasks to complete.
 void waitForTaskCount(int num)
          Wait until there are no more than num tasks in the queue.
 
Methods inherited from class java.util.concurrent.ThreadPoolExecutor
awaitTermination, execute, finalize, getActiveCount, getCompletedTaskCount, getCorePoolSize, getKeepAliveTime, getLargestPoolSize, getMaximumPoolSize, getPoolSize, getQueue, getRejectedExecutionHandler, getTaskCount, getThreadFactory, isShutdown, isTerminated, isTerminating, prestartAllCoreThreads, prestartCoreThread, purge, remove, setCorePoolSize, setKeepAliveTime, setMaximumPoolSize, setRejectedExecutionHandler, setThreadFactory, shutdown, shutdownNow, terminated
 
Methods inherited from class java.util.concurrent.AbstractExecutorService
invokeAll, invokeAll, invokeAny, invokeAny, submit, submit, submit
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ThreadPool

public ThreadPool(String name,
                  int n,
                  int max,
                  int prio,
                  BlockingQueue<Runnable> q)
Get an instance of ThreadPool.

Parameters:
name - the name of this pool
n - the core size of this pool
max - the maximum size of this pool
prio - the priority of threads created within this pool
q - the work queue

ThreadPool

public ThreadPool(String name,
                  int n,
                  int max,
                  int prio,
                  int size)
Get an instance of ThreadPool.

Parameters:
name - Name of the pool.
n - number of threads
max - the maximum number of threads
prio - Priority of the child threads.
size - the queue size (as an ArrayBlockingQueue)

ThreadPool

public ThreadPool(String name,
                  int n,
                  int max,
                  int prio)
Get an instance of ThreadPool.

Parameters:
name - name of the pool
n - core pool size
max - max pool size
prio - priority of threads created within this pool

ThreadPool

public ThreadPool(String name,
                  int n,
                  int max)
Get an instance of ThreadPool.

Parameters:
name - name of the pool
n - core pool size
max - max pool size

ThreadPool

public ThreadPool(String name,
                  int n)
Get an instance of ThreadPool.

Parameters:
name - Name of the pool.
n - Number of threads.

ThreadPool

public ThreadPool(String name)
Get an instance of ThreadPool with five threads and a normal priority.

Parameters:
name - Name of the pool.
Method Detail

start

public void start()
Start the ThreadPool.


getIdleThreadCount

public int getIdleThreadCount()
Find out how many threads are idle. This is a snapshot, it is subject to change between the time that the number is calculated and the time that the value is returned.

Returns:
the number of threads not currently running a task

toString

public String toString()
String me.

Overrides:
toString in class Object

getMinTotalThreads

public int getMinTotalThreads()
Get the minimum number of threads that may exist in the thread pool at any moment.


getPriority

public int getPriority()
Get the priority that will be used for any new threads within this thread group.


setPriority

public void setPriority(int p)
Set the priority to be used for any new threads within this threaad group.


getMonitor

public ThreadPoolObserver getMonitor()
Get the monitor that receives notifications when a worker thread finishes a job.


setMonitor

public void setMonitor(ThreadPoolObserver m)
Set the observer who will receive notification whenever a task is completed.


beforeExecute

protected void beforeExecute(Thread t,
                             Runnable r)
Overrides:
beforeExecute in class ThreadPoolExecutor

afterExecute

protected void afterExecute(Runnable r,
                            Throwable t)
Overrides:
afterExecute in class ThreadPoolExecutor

addTask

public void addTask(Runnable r)
Add a task for one of the threads to execute. This method will add a new task to the queue and notify the queue of the new task (as well as notify the pool manager) then return immediately.

Throws:
IndexOutOfBoundsException - if the backing list is full
See Also:
ThreadPoolRunnable

addTask

public boolean addTask(Runnable r,
                       long timeout)
Add a task for one of the threads to execute. This method will add a new task to the queue, but only wait a certain amount of time for the task to get picked up. If the task is not picked up for execution by timeout milliseconds, the task will not be executed.

Parameters:
r - the task to execute
timeout - the number of milliseconds to wait for it to start
Returns:
true if the task was started
Throws:
IndexOutOfBoundsException - if the backing list is full

waitForCompletion

public void waitForCompletion()
                       throws InterruptedException
Shut down all of the threads after all jobs are complete, and wait for all tasks to complete.

This is a convenience method that calls waitforTaskCount(0), followed by shutdown(), followed by waitForThreads().

Throws:
InterruptedException - if waitForTaskCount or waitForThreads throws an exception

waitForTaskCount

public void waitForTaskCount(int num)
                      throws InterruptedException
Wait until there are no more than num tasks in the queue. This is good for throttling task additions.

Parameters:
num - the number of tasks for which to wait
Throws:
InterruptedException - if wait fails


Copyright © 1995-2007 SPY Internetworking. All Rights Reserved.