java.lang.ObjectEDU.oswego.cs.dl.util.concurrent.ThreadFactoryUser
EDU.oswego.cs.dl.util.concurrent.PooledExecutor
All Implemented Interfaces:
Executor
execute(Runnable command)
, which can be
called instead of directly creating threads to execute commands.
Thread pools can be useful for several, usually intertwined reasons:
When given a choice, this pool always prefers adding a new thread rather than queueing if there are currently fewer than the current getMinimumPoolSize threads running, but otherwise always prefers queuing a request rather than adding a new thread. Thus, if you use an unbounded buffer, you will never have more than getMinimumPoolSize threads running. (Since the default minimumPoolSize is one, you will probably want to explicitly setMinimumPoolSize.)
While queuing can be useful in smoothing out transient bursts of requests, especially in socket-based services, it is not very well behaved when commands continue to arrive on average faster than they can be processed. Using bounds for both the queue and the pool size, along with run-when-blocked policy is often a reasonable response to such possibilities.
Queue sizes and maximum pool sizes can often be traded off for each other. Using large queues and small pools minimizes CPU usage, OS resources, and context-switching overhead, but can lead to artifically low throughput. Especially if tasks frequently block (for example if they are I/O bound), a JVM and underlying OS may be able to schedule time for more threads than you otherwise allow. Use of small queues or queueless handoffs generally requires larger pool sizes, which keeps CPUs busier but may encounter unacceptable scheduling overhead, which also decreases throughput.
execute
request arrives. The default
value is (for all practical purposes) infinite --
Integer.MAX_VALUE
, so should be set in the
constructor or the set method unless you are just using the pool
to minimize construction overhead. Because task handoffs to idle
worker threads require synchronization that in turn relies on JVM
scheduling policies to ensure progress, it is possible that a new
thread will be created even though an existing worker thread has
just become idle but has not progressed to the point at which it
can accept a new task. This phenomenon tends to occur on some
JVMs when bursts of short tasks are executed.
To establish worker threads permanently, use a negative argument to setKeepAliveTime.
execute
requests to
block. There are four supported policies for handling this
problem, and mechanics (based on the Strategy Object pattern) to
allow others in subclasses:
execute
request
runs the task itself. This policy helps guard against lockup.
These cases can never occur if the maximum pool size is unbounded
or the queue is unbounded. In these cases you instead face
potential resource exhaustion.) The execute method does not
throw any checked exceptions in any of these cases since any
errors associated with them must normally be dealt with via
handlers or callbacks. (Although in some cases, these might be
associated with throwing unchecked exceptions.) You may wish to
add special implementations even if you choose one of the listed
policies. For example, the supplied Discard policy does not
inform the caller of the drop. You could add your own version
that does so. Since choice of policies is normally a system-wide
decision, selecting a policy affects all calls to
execute
. If for some reason you would instead like
to make per-call decisions, you could add variant versions of the
execute
method (for example,
executeIfWouldNotBlock
) in subclasses.
Also, if you are using some form of queuing, you may wish to call method drain() to remove (and return) unprocessed commands from the queue after shutting down the pool and its clients. If you need to be sure these commands are processed, you can then run() each of the commands in the list returned by drain().
Usage examples.
Probably the most common use of pools is in statics or singletons accessible from a number of classes in a package; for example:
class MyPool { // initialize to use a maximum of 8 threads. static PooledExecutor pool = new PooledExecutor(8); }Here are some sample variants in initialization:
pool = new PooledExecutor(new BoundedBuffer(10), 100); pool.setMinimumPoolSize(4);
pool = new PooledExecutor(new BoundedBuffer(10), 100); pool.setMinimumPoolSize(4); pool.setKeepAliveTime(1000 * 60 * 5); pool.createThreads(9);
pool = new PooledExecutor(new BoundedBuffer(10), 100); pool.setMinimumPoolSize(4); pool.setKeepAliveTime(1000 * 60 * 5); pool.waitWhenBlocked(); pool.createThreads(9);
pool = new PooledExecutor(new LinkedQueue()); pool.setKeepAliveTime(-1); // live forever pool.createThreads(5);
Usage notes.
Pools do not mesh well with using thread-specific storage via java.lang.ThreadLocal. ThreadLocal relies on the identity of a thread executing a particular task. Pools use the same thread to perform different tasks.
If you need a policy not handled by the parameters in this class consider writing a subclass.
Version note: Previous versions of this class relied on ThreadGroups for aggregate control. This has been removed, and the method interruptAll added, to avoid differences in behavior across JVMs.
[ Introduction to this package. ]
Nested Class Summary: | ||
---|---|---|
protected class | PooledExecutor.Worker | Class defining the basic run loop for pooled threads. * |
public interface | PooledExecutor.BlockedExecutionHandler | Class for actions to take when execute() blocks. Uses Strategy pattern to represent different actions. You can add more in subclasses, and/or create subclasses of these. If so, you will also want to add or modify the corresponding methods that set the current blockedExectionHandler_. * |
protected class | PooledExecutor.RunWhenBlocked | Class defining Run action. * |
protected class | PooledExecutor.WaitWhenBlocked | Class defining Wait action. * |
protected class | PooledExecutor.DiscardWhenBlocked | Class defining Discard action. * |
protected class | PooledExecutor.AbortWhenBlocked | Class defining Abort action. * |
public class | PooledExecutor.AbortException | |
protected class | PooledExecutor.DiscardOldestWhenBlocked | Class defining DiscardOldest action. Under this policy, at most one old unhandled task is discarded. If the new task can then be handed off, it is. Otherwise, the new task is run in the current thread (i.e., RunWhenBlocked is used as a backup policy.) * |
Field Summary | ||
---|---|---|
public static final int | DEFAULT_MAXIMUMPOOLSIZE | The maximum pool size; used if not otherwise specified. Default value is essentially infinite (Integer.MAX_VALUE) |
public static final int | DEFAULT_MINIMUMPOOLSIZE | The minimum pool size; used if not otherwise specified. Default value is 1. * |
public static final long | DEFAULT_KEEPALIVETIME | The maximum time to keep worker threads alive waiting for new tasks; used if not otherwise specified. Default value is one minute (60000 milliseconds). |
protected int | maximumPoolSize_ | The maximum number of threads allowed in pool. |
protected int | minimumPoolSize_ | The minumum number of threads to maintain in pool. |
protected int | poolSize_ | Current pool size. |
protected long | keepAliveTime_ | The maximum time for an idle thread to wait for new task. |
protected boolean | shutdown_ | Shutdown flag - latches true when a shutdown method is called in order to disable queuing/handoffs of new tasks. |
protected final Channel | handOff_ | The channel used to hand off the command to a thread in the pool. * |
protected final Map | threads_ | The set of active threads, declared as a map from workers to their threads. This is needed by the interruptAll method. It may also be useful in subclasses that need to perform other thread management chores. |
protected BlockedExecutionHandler | blockedExecutionHandler_ | The current handler for unserviceable requests. * |
Fields inherited from EDU.oswego.cs.dl.util.concurrent.ThreadFactoryUser: |
---|
threadFactory_ |
Constructor: |
---|
|
|
|
|
Methods from EDU.oswego.cs.dl.util.concurrent.ThreadFactoryUser: |
---|
getThreadFactory, setThreadFactory |
Methods from java.lang.Object: |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Method from EDU.oswego.cs.dl.util.concurrent.PooledExecutor Detail: |
---|
|
|
|
|
|
|
|
List tasks = pool.drain(); for (Iterator it = tasks.iterator(); it.hasNext();) ( (Runnable)(it.next()) ).run(); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|