ThreadPoolExecutor Class

Definition

An ExecutorService that executes each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods.

[Android.Runtime.Register("java/util/concurrent/ThreadPoolExecutor", DoNotGenerateAcw=true)]
public class ThreadPoolExecutor : Java.Util.Concurrent.AbstractExecutorService
[<Android.Runtime.Register("java/util/concurrent/ThreadPoolExecutor", DoNotGenerateAcw=true)>]
type ThreadPoolExecutor = class
    inherit AbstractExecutorService
Inheritance
Derived
Attributes

Remarks

An ExecutorService that executes each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods.

Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.

To be useful across a wide range of contexts, this class provides many adjustable parameters and extensibility hooks. However, programmers are urged to use the more convenient Executors factory methods Executors#newCachedThreadPool (unbounded thread pool, with automatic thread reclamation), Executors#newFixedThreadPool (fixed size thread pool) and Executors#newSingleThreadExecutor (single background thread), that preconfigure settings for the most common usage scenarios. Otherwise, use the following guide when manually configuring and tuning this class:

<dl>

<dt>Core and maximum pool sizes</dt>

<dd>A ThreadPoolExecutor will automatically adjust the pool size (see #getPoolSize) according to the bounds set by corePoolSize (see #getCorePoolSize) and maximumPoolSize (see #getMaximumPoolSize).

When a new task is submitted in method #execute(Runnable), if fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle. Else if fewer than maximumPoolSize threads are running, a new thread will be created to handle the request only if the queue is full. By setting corePoolSize and maximumPoolSize the same, you create a fixed-size thread pool. By setting maximumPoolSize to an essentially unbounded value such as Integer.MAX_VALUE, you allow the pool to accommodate an arbitrary number of concurrent tasks. Most typically, core and maximum pool sizes are set only upon construction, but they may also be changed dynamically using #setCorePoolSize and #setMaximumPoolSize. </dd>

<dt>On-demand construction</dt>

<dd>By default, even core threads are initially created and started only when new tasks arrive, but this can be overridden dynamically using method #prestartCoreThread or #prestartAllCoreThreads. You probably want to prestart threads if you construct the pool with a non-empty queue. </dd>

<dt>Creating new threads</dt>

<dd>New threads are created using a ThreadFactory. If not otherwise specified, a Executors#defaultThreadFactory is used, that creates threads to all be in the same ThreadGroup and with the same NORM_PRIORITY priority and non-daemon status. By supplying a different ThreadFactory, you can alter the thread's name, thread group, priority, daemon status, etc. If a ThreadFactory fails to create a thread when asked by returning null from newThread, the executor will continue, but might not be able to execute any tasks. Threads should possess the "modifyThread" RuntimePermission. If worker threads or other threads using the pool do not possess this permission, service may be degraded: configuration changes may not take effect in a timely manner, and a shutdown pool may remain in a state in which termination is possible but not completed.</dd>

<dt>Keep-alive times</dt>

<dd>If the pool currently has more than corePoolSize threads, excess threads will be terminated if they have been idle for more than the keepAliveTime (see #getKeepAliveTime(TimeUnit)). This provides a means of reducing resource consumption when the pool is not being actively used. If the pool becomes more active later, new threads will be constructed. This parameter can also be changed dynamically using method #setKeepAliveTime(long, TimeUnit). Using a value of Long.MAX_VALUETimeUnit#NANOSECONDS effectively disables idle threads from ever terminating prior to shut down. By default, the keep-alive policy applies only when there are more than corePoolSize threads, but method #allowCoreThreadTimeOut(boolean) can be used to apply this time-out policy to core threads as well, so long as the keepAliveTime value is non-zero. </dd>

<dt>Queuing</dt>

<dd>Any BlockingQueue may be used to transfer and hold submitted tasks. The use of this queue interacts with pool sizing:

<ul>

<li>If fewer than corePoolSize threads are running, the Executor always prefers adding a new thread rather than queuing.

<li>If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread.

<li>If a request cannot be queued, a new thread is created unless this would exceed maximumPoolSize, in which case, the task will be rejected.

</ul>

There are three general strategies for queuing: <ol>

<li><em> Direct handoffs.</em> A good default choice for a work queue is a SynchronousQueue that hands off tasks to threads without otherwise holding them. Here, an attempt to queue a task will fail if no threads are immediately available to run it, so a new thread will be constructed. This policy avoids lockups when handling sets of requests that might have internal dependencies. Direct handoffs generally require unbounded maximumPoolSizes to avoid rejection of new submitted tasks. This in turn admits the possibility of unbounded thread growth when commands continue to arrive on average faster than they can be processed.

<li><em> Unbounded queues.</em> Using an unbounded queue (for example a LinkedBlockingQueue without a predefined capacity) will cause new tasks to wait in the queue when all corePoolSize threads are busy. Thus, no more than corePoolSize threads will ever be created. (And the value of the maximumPoolSize therefore doesn't have any effect.) This may be appropriate when each task is completely independent of others, so tasks cannot affect each others execution; for example, in a web page server. While this style of queuing can be useful in smoothing out transient bursts of requests, it admits the possibility of unbounded work queue growth when commands continue to arrive on average faster than they can be processed.

<li><em>Bounded queues.</em> A bounded queue (for example, an ArrayBlockingQueue) helps prevent resource exhaustion when used with finite maximumPoolSizes, but can be more difficult to tune and control. Queue sizes and maximum pool sizes may 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 artificially low throughput. If tasks frequently block (for example if they are I/O bound), a system may be able to schedule time for more threads than you otherwise allow. Use of small queues generally requires larger pool sizes, which keeps CPUs busier but may encounter unacceptable scheduling overhead, which also decreases throughput.

</ol>

</dd>

<dt>Rejected tasks</dt>

<dd>New tasks submitted in method #execute(Runnable) will be <em>rejected</em> when the Executor has been shut down, and also when the Executor uses finite bounds for both maximum threads and work queue capacity, and is saturated. In either case, the execute method invokes the RejectedExecutionHandler#rejectedExecution(Runnable, ThreadPoolExecutor) method of its RejectedExecutionHandler. Four predefined handler policies are provided:

<ol>

<li>In the default ThreadPoolExecutor.AbortPolicy, the handler throws a runtime RejectedExecutionException upon rejection.

<li>In ThreadPoolExecutor.CallerRunsPolicy, the thread that invokes execute itself runs the task. This provides a simple feedback control mechanism that will slow down the rate that new tasks are submitted.

<li>In ThreadPoolExecutor.DiscardPolicy, a task that cannot be executed is simply dropped. This policy is designed only for those rare cases in which task completion is never relied upon.

<li>In ThreadPoolExecutor.DiscardOldestPolicy, if the executor is not shut down, the task at the head of the work queue is dropped, and then execution is retried (which can fail again, causing this to be repeated.) This policy is rarely acceptable. In nearly all cases, you should also cancel the task to cause an exception in any component waiting for its completion, and/or log the failure, as illustrated in ThreadPoolExecutor.DiscardOldestPolicy documentation.

</ol>

It is possible to define and use other kinds of RejectedExecutionHandler classes. Doing so requires some care especially when policies are designed to work only under particular capacity or queuing policies. </dd>

<dt>Hook methods</dt>

<dd>This class provides protected overridable #beforeExecute(Thread, Runnable) and #afterExecute(Runnable, Throwable) methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries. Additionally, method #terminated can be overridden to perform any special processing that needs to be done once the Executor has fully terminated.

If hook, callback, or BlockingQueue methods throw exceptions, internal worker threads may in turn fail, abruptly terminate, and possibly be replaced.</dd>

<dt>Queue maintenance</dt>

<dd>Method #getQueue() allows access to the work queue for purposes of monitoring and debugging. Use of this method for any other purpose is strongly discouraged. Two supplied methods, #remove(Runnable) and #purge are available to assist in storage reclamation when large numbers of queued tasks become cancelled.</dd>

<dt>Reclamation</dt>

<dd>A pool that is no longer referenced in a program <em>AND</em> has no remaining threads may be reclaimed (garbage collected) without being explicitly shutdown. You can configure a pool to allow all unused threads to eventually die by setting appropriate keep-alive times, using a lower bound of zero core threads and/or setting #allowCoreThreadTimeOut(boolean). </dd>

</dl>

<b>Extension example.</b> Most extensions of this class override one or more of the protected hook methods. For example, here is a subclass that adds a simple pause/resume feature:

{@code
            class PausableThreadPoolExecutor extends ThreadPoolExecutor {
              private boolean isPaused;
              private ReentrantLock pauseLock = new ReentrantLock();
              private Condition unpaused = pauseLock.newCondition();

              public PausableThreadPoolExecutor(...) { super(...); }

              protected void beforeExecute(Thread t, Runnable r) {
                super.beforeExecute(t, r);
                pauseLock.lock();
                try {
                  while (isPaused) unpaused.await();
                } catch (InterruptedException ie) {
                  t.interrupt();
                } finally {
                  pauseLock.unlock();
                }
              }

              public void pause() {
                pauseLock.lock();
                try {
                  isPaused = true;
                } finally {
                  pauseLock.unlock();
                }
              }

              public void resume() {
                pauseLock.lock();
                try {
                  isPaused = false;
                  unpaused.signalAll();
                } finally {
                  pauseLock.unlock();
                }
              }
            }}

Added in 1.5.

Java documentation for java.util.concurrent.ThreadPoolExecutor.

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

ThreadPoolExecutor(Int32, Int32, Int64, TimeUnit, IBlockingQueue)

Creates a new ThreadPoolExecutor with the given initial parameters, the Executors#defaultThreadFactory default thread factory and the ThreadPoolExecutor.

ThreadPoolExecutor(Int32, Int32, Int64, TimeUnit, IBlockingQueue, IRejectedExecutionHandler)

Creates a new ThreadPoolExecutor with the given initial parameters and the Executors#defaultThreadFactory default thread factory.

ThreadPoolExecutor(Int32, Int32, Int64, TimeUnit, IBlockingQueue, IThreadFactory)

Creates a new ThreadPoolExecutor with the given initial parameters and the ThreadPoolExecutor.

ThreadPoolExecutor(Int32, Int32, Int64, TimeUnit, IBlockingQueue, IThreadFactory, IRejectedExecutionHandler)

Creates a new ThreadPoolExecutor with the given initial parameters.

ThreadPoolExecutor(IntPtr, JniHandleOwnership)

A constructor used when creating managed representations of JNI objects; called by the runtime.

Properties

ActiveCount

Returns the approximate number of threads that are actively executing tasks.

Class

Returns the runtime class of this Object.

(Inherited from Object)
CompletedTaskCount

Returns the approximate total number of tasks that have completed execution.

CorePoolSize

Returns the core number of threads. -or- Sets the core number of threads.

Handle

The handle to the underlying Android instance.

(Inherited from Object)
IsShutdown
IsTerminated
IsTerminating

Returns true if this executor is in the process of terminating after #shutdown or #shutdownNow but has not completely terminated.

JniIdentityHashCode (Inherited from Object)
JniPeerMembers
LargestPoolSize

Returns the largest number of threads that have ever simultaneously been in the pool.

MaximumPoolSize

Returns the maximum allowed number of threads. -or- Sets the maximum allowed number of threads.

PeerReference (Inherited from Object)
PoolSize

Returns the current number of threads in the pool.

Queue

Returns the task queue used by this executor.

RejectedExecutionHandler

Returns the current handler for unexecutable tasks. -or- Sets a new handler for unexecutable tasks.

TaskCount

Returns the approximate total number of tasks that have ever been scheduled for execution.

ThreadFactory

Returns the thread factory used to create new threads. -or- Sets the thread factory used to create new threads.

ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

ThresholdType

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

AfterExecute(IRunnable, Throwable)

Method invoked upon completion of execution of the given Runnable.

AllowCoreThreadTimeOut(Boolean)

Sets the policy governing whether core threads may time out and terminate if no tasks arrive within the keep-alive time, being replaced if needed when new tasks arrive.

AllowsCoreThreadTimeOut()

Returns true if this pool allows core threads to time out and terminate if no tasks arrive within the keepAlive time, being replaced if needed when new tasks arrive.

AwaitTermination(Int64, TimeUnit)
AwaitTerminationAsync(Int64, TimeUnit) (Inherited from AbstractExecutorService)
BeforeExecute(Thread, IRunnable)

Method invoked prior to executing the given Runnable in the given thread.

Clone()

Creates and returns a copy of this object.

(Inherited from Object)
Dispose() (Inherited from Object)
Dispose(Boolean) (Inherited from Object)
Equals(Object)

Indicates whether some other object is "equal to" this one.

(Inherited from Object)
Execute(IRunnable)

Executes the given task sometime in the future.

GetHashCode()

Returns a hash code value for the object.

(Inherited from Object)
GetKeepAliveTime(TimeUnit)

Returns the thread keep-alive time, which is the amount of time that threads may remain idle before being terminated.

InvokeAll(ICollection) (Inherited from AbstractExecutorService)
InvokeAll(ICollection, Int64, TimeUnit) (Inherited from AbstractExecutorService)
InvokeAny(ICollection) (Inherited from AbstractExecutorService)
InvokeAny(ICollection, Int64, TimeUnit) (Inherited from AbstractExecutorService)
JavaFinalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

(Inherited from Object)
NewTaskFor(ICallable)

Returns a RunnableFuture for the given callable task.

(Inherited from AbstractExecutorService)
NewTaskFor(IRunnable, Object)

Returns a RunnableFuture for the given runnable and default value.

(Inherited from AbstractExecutorService)
Notify()

Wakes up a single thread that is waiting on this object's monitor.

(Inherited from Object)
NotifyAll()

Wakes up all threads that are waiting on this object's monitor.

(Inherited from Object)
PrestartAllCoreThreads()

Starts all core threads, causing them to idly wait for work.

PrestartCoreThread()

Starts a core thread, causing it to idly wait for work.

Purge()

Tries to remove from the work queue all Future tasks that have been cancelled.

Remove(IRunnable)

Removes this task from the executor's internal queue if it is present, thus causing it not to be run if it has not already started.

SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Object)
SetKeepAliveTime(Int64, TimeUnit)

Sets the thread keep-alive time, which is the amount of time that threads may remain idle before being terminated.

Shutdown()

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

ShutdownNow()

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

Submit(ICallable) (Inherited from AbstractExecutorService)
Submit(IRunnable)

Submits a Runnable task for execution and returns a Future representing that task.

(Inherited from AbstractExecutorService)
Submit(IRunnable, Object) (Inherited from AbstractExecutorService)
Terminated()

Method invoked when the Executor has terminated.

ToArray<T>() (Inherited from Object)
ToString()

Returns a string representation of the object.

(Inherited from Object)
UnregisterFromRuntime() (Inherited from Object)
Wait()

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>.

(Inherited from Object)
Wait(Int64)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)
Wait(Int64, Int32)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Object)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Object)
IJavaPeerable.Finalized() (Inherited from Object)
IJavaPeerable.JniManagedPeerState (Inherited from Object)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Object)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Object)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Object)

Extension Methods

JavaCast<TResult>(IJavaObject)

Performs an Android runtime-checked type conversion.

JavaCast<TResult>(IJavaObject)
GetJniTypeName(IJavaPeerable)
AwaitTerminationAsync(IExecutorService, Int64, TimeUnit)
InvokeAnyAsync(IExecutorService, ICollection)
InvokeAnyAsync(IExecutorService, ICollection, Int64, TimeUnit)

Applies to