C# Class Java.Util.Concurrent.ThreadPoolExecutor

Mostrar archivo Open project: Elders/Hystrix.NET Class Usage Examples

Private Properties

Property Type Description
AddWorker bool
AdvanceRunState void
ClearInterruptsForTaskRun void
CompareAndDecrementWorkerCount bool
CompareAndIncrementWorkerCount bool
ControlOf int
DecrementWorkerCount void
DrainQueue IList
GetTask IRunnable
InterruptIdleWorkers void
InterruptIdleWorkers void
InterruptWorkers void
IsRunning bool
IsRunningOrShutdown bool
ProcessWorkerExit void
Reject void
RunStateAtLeast bool
RunStateLessThan bool
RunStateOf int
RunWorker void
TryTerminate void
WorkerCountOf int

Public Methods

Method Description
AwaitTermination ( System.TimeSpan duration ) : bool

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Dispose ( ) : void

Shutsdown and disposes of this ThreadPoolExecutor.

PreStartAllCoreThreads ( ) : int

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

This overrides the default policy of starting core threads only when new tasks are executed.

PreStartCoreThread ( ) : bool

Starts a core thread, causing it to idly wait for work. This overrides the default policy of starting core threads only when new tasks are executed. This method will return false if all core threads have already been started.

Purge ( ) : void

Tries to remove from the work queue all IFuture{T} tasks that have been cancelled. This method can be useful as a storage reclamation operation, that has no other impact on functionality. Cancelled tasks are never executed, but may accumulate in work queues until worker threads can actively remove them. Invoking this method instead tries to remove them now. However, this method may fail to remove tasks in the presence of interference by other threads.

Remove ( System.Action task ) : bool

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.

This method may be useful as one part of a cancellation scheme. It may fail to remove tasks that have been converted into other forms before being placed on the internal queue. For example, a task entered using IExecutorService.Submit(Action) might be converted into a form that maintains IFuture{T} status. However, in such cases, method Purge may be used to remove those Futures that have been cancelled.

Remove ( IRunnable task ) : bool

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.

This method may be useful as one part of a cancellation scheme. It may fail to remove tasks that have been converted into other forms before being placed on the internal queue. For example, a task entered using IExecutorService.Submit(Action) might be converted into a form that maintains IFuture{T} status. However, in such cases, method Purge may be used to remove those Futures that have been cancelled.

Shutdown ( ) : void

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.

ShutdownNow ( ) : IList

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution. These tasks are drained (removed) from the task queue upon return from this method.

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. This implementation cancels tasks via Thread.Interrupt, so any task that fails to respond to interrupts may never terminate.

ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, System.TimeSpan keepAliveTime, IBlockingQueue workQueue ) : System

Creates a new ThreadPoolExecutor with the given initial parameters and default thread factory and rejected execution handler.

> It may be more convenient to use one of the Executors factory methods instead of this general purpose constructor.

ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, System.TimeSpan keepAliveTime, IBlockingQueue workQueue, IRejectedExecutionHandler handler ) : System

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

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

ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, System.TimeSpan keepAliveTime, IBlockingQueue workQueue, IThreadFactory threadFactory ) : System

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

ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, System.TimeSpan keepAliveTime, IBlockingQueue workQueue, IThreadFactory threadFactory, IRejectedExecutionHandler handler ) : System

Creates a new ThreadPoolExecutor with the given initial parameters.

Protected Methods

Method Description
AfterExecute ( IRunnable runnable, Exception exception ) : void

Method invoked upon completion of execution of the given Runnable. This method is invoked by the thread that executed the task. If non-null, the exception is the unhandle exception that caused execution to terminate abruptly.

This implementation does nothing, but may be customized in subclasses. Note: To properly nest multiple overridings, subclasses should generally invoke base.AfterExecute at the beginning of this method.

Note: When actions are enclosed in tasks (such as FutureTask{T}) either explicitly or via methods such as IExecutorService.Submit(System.Action), these task objects catch and maintain computational exceptions, and so they do not cause abrupt termination, and the internal exceptions are not passed to this method. If you would like to trap both kinds of failures in this method, you can further probe for such cases, as in this sample subclass that prints either the direct cause or the underlying exception if a task has been aborted:

class ExtendedExecutor : ThreadPoolExecutor { // ... protected void AfterExecute(IRunnable r, Exception t) { base.AfterExecute(r, t); if (t == null && r is IFuture) { try { Object result = ((IFuture) r).Get(); } catch (CancellationException ce) { t = ce; } catch (ExecutionException ee) { t = ee.InnerException; } catch (InterruptedException ie) { Thread.CurrentThread.Interrupt(); // ignore/reset } } if (t != null) Console.WriteLine(t); } }
BeforeExecute ( System.Thread thread, IRunnable runnable ) : void

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

This method is invoked by thread that will execute runnable, and may be used to re-initialize ThreadLocals, or to perform logging. This implementation does nothing, but may be customized in subclasses. Note: To properly nest multiple overridings, subclasses should generally invoke base.BeforeExecute at the end of this method.

Dispose ( bool disposing ) : void

Helper method to dispose of this ThreadPoolExecutor

DoExecute ( IRunnable command ) : void

Executes the given task sometime in the future. The task may execute in a new thread or in an existing pooled thread.

If the task cannot be submitted for execution, either because this executor has been shutdown or because its capacity has been reached, the task is handled by the current IRejectedExecutionHandler for this ThreadPoolExecutor.

OnShutdown ( ) : void

Performs any further cleanup following run state transition on invocation of shutdown. A no-op here, but used by ScheduledThreadPoolExecutor to cancel delayed tasks.

Terminated ( ) : void

Method invoked when the IExecutor has terminated. Default implementation does nothing.

Note: To properly nest multiple overridings, subclasses should generally invoke base.terminated within this method.

Private Methods

Method Description
AddWorker ( IRunnable firstTask, bool core ) : bool

Checks if a new worker can be added with respect to current pool state and the given bound (either core or maximum). If so, the worker count is adjusted accordingly, and, if possible, a new worker is created and started running firstTask as its first task. This method returns false if the pool is stopped or eligible to shut down. It also returns false if the thread factory fails to create a thread when asked, which requires a backout of workerCount, and a recheck for termination, in case the existence of this worker was holding up termination.

AdvanceRunState ( int targetState ) : void

Transitions control state to given target or leaves if alone if already at least the given target.

ClearInterruptsForTaskRun ( ) : void

Ensures that unless the pool is stopping, the current thread does not have its interrupt set. This requires a double-check of state in case the interrupt was cleared concurrently with a shutdownNow -- if so, the interrupt is re-enabled.

CompareAndDecrementWorkerCount ( int expect ) : bool

Attempt to CAS-decrement the workerCount field of control state.

CompareAndIncrementWorkerCount ( int expect ) : bool

Attempt to CAS-increment the workerCount field of control state.

ControlOf ( int rs, int wc ) : int
DecrementWorkerCount ( ) : void

Decrements the workerCount field of ctl. This is called only on abrupt termination of a thread (see ProcessWorkerExit). Other decrements are performed within GetTask.

DrainQueue ( ) : IList

Drains the task queue into a new list, normally using drainTo. But if the queue is a DelayQueue or any other kind of queue for which poll or drainTo may fail to remove some elements, it deletes them one by one.

GetTask ( ) : IRunnable

Performs blocking or timed wait for a task, depending on current configuration settings, or returns null if this worker must exit because of any of: 1. There are more than maximumPoolSize workers (due to a call to setMaximumPoolSize). 2. The pool is stopped. 3. The pool is shutdown and the queue is empty. 4. This worker timed out waiting for a task, and timed-out workers are subject to termination (that is, allowCoreThreadTimeOut || workerCount > corePoolSize) both before and after the timed wait.

InterruptIdleWorkers ( ) : void

Interrupts all threads that might be waiting for tasks.

InterruptIdleWorkers ( bool onlyOne ) : void

Interrupts threads that might be waiting for tasks (as indicated by not being locked) so they can check for termination or configuration changes. Ignores SecurityExceptions (in which case some threads may remain uninterrupted). @param onlyOne If true, interrupt at most one worker. This is called only from TryTerminate when termination is otherwise enabled but there are still other workers. In this case, at most one waiting worker is interrupted to propagate shutdown signals in case all threads are currently waiting. Interrupting any arbitrary thread ensures that newly arriving workers since shutdown began will also eventually exit. To guarantee eventual termination, it suffices to always interrupt only one idle worker, but shutdown() interrupts all idle workers so that redundant workers exit promptly, not waiting for a straggler task to finish.

InterruptWorkers ( ) : void

Interrupts all threads, even if active. Ignores SecurityExceptions (in which case some threads may remain uninterrupted).

IsRunning ( int c ) : bool
IsRunningOrShutdown ( bool shutdownOK ) : bool

State check needed by ScheduledThreadPoolExecutor to enable running tasks during shutdown.

ProcessWorkerExit ( Worker w, bool completedAbruptly ) : void

Performs cleanup and bookkeeping for a dying worker. Called only from worker threads. Unless completedAbruptly is set, assumes that workerCount has already been adjusted to account for exit. This method removes thread from worker set, and possibly terminates the pool or replaces the worker if either it exited due to user task exception or if fewer than corePoolSize workers are running or queue is non-empty but there are no workers. the worker if the worker died to the user exception

Reject ( IRunnable command ) : void

Invokes the rejected execution handler for the given command.

RunStateAtLeast ( int c, int s ) : bool
RunStateLessThan ( int c, int s ) : bool

Bit field accessors that don't require unpacking _controlState. These depend on the bit layout and on workerCount being never negative.

RunStateOf ( int c ) : int
RunWorker ( Worker worker ) : void

Main worker run loop. Repeatedly gets tasks from queue and executes them, while coping with a number of issues: 1. We may start out with an initial task, in which case we don't need to get the first one. Otherwise, as long as pool is running, we get tasks from GetTask. If it returns null then the worker exits due to changed pool state or configuration parameters. Other exits result from exception throws in external code, in which case completedAbruptly holds, which usually leads ProcessWorkerExit to replace this thread. 2. Before running any task, the lock is acquired to prevent other pool interrupts while the task is executing, and ClearInterruptsForTaskRun called to ensure that unless pool is stopping, this thread does not have its interrupt set. 3. Each task run is preceded by a call to BeforeExecute, which might throw an exception, in which case we cause thread to die (breaking loop with completedAbruptly true) without processing the task. 4. Assuming BeforeExecute completes normally, we run the task, gathering any of its thrown exceptions to send to AfterExecute. We separately handle RuntimeException, Error (both of which the specs guarantee that we trap) and arbitrary Throwables. Because we cannot rethrow Throwables within Runnable.run, we wrap them within Errors on the way out (to the thread's UncaughtExceptionHandler). Any thrown exception also conservatively causes thread to die. 5. After task.run completes, we call AfterExecute, which may also throw an exception, which will also cause thread to die. According to JLS Sec 14.20, this exception is the one that will be in effect even if task.run throws. The net effect of the exception mechanics is that AfterExecute and the thread's UncaughtExceptionHandler have as accurate information as we can provide about any problems encountered by user code. the worker to run

TryTerminate ( ) : void

Transitions to TERMINATED state if either (SHUTDOWN and pool and queue empty) or (STOP and pool empty). If otherwise eligible to terminate but workerCount is nonzero, interrupts an idle worker to ensure that shutdown signals propagate. This method must be called following any action that might make termination possible -- reducing worker count or removing tasks from the queue during shutdown. The method is non-private to allow access from ScheduledThreadPoolExecutor.

WorkerCountOf ( int c ) : int

Method Details

AfterExecute() protected method

Method invoked upon completion of execution of the given Runnable. This method is invoked by the thread that executed the task. If non-null, the exception is the unhandle exception that caused execution to terminate abruptly.

This implementation does nothing, but may be customized in subclasses. Note: To properly nest multiple overridings, subclasses should generally invoke base.AfterExecute at the beginning of this method.

Note: When actions are enclosed in tasks (such as FutureTask{T}) either explicitly or via methods such as IExecutorService.Submit(System.Action), these task objects catch and maintain computational exceptions, and so they do not cause abrupt termination, and the internal exceptions are not passed to this method. If you would like to trap both kinds of failures in this method, you can further probe for such cases, as in this sample subclass that prints either the direct cause or the underlying exception if a task has been aborted:

class ExtendedExecutor : ThreadPoolExecutor { // ... protected void AfterExecute(IRunnable r, Exception t) { base.AfterExecute(r, t); if (t == null && r is IFuture) { try { Object result = ((IFuture) r).Get(); } catch (CancellationException ce) { t = ce; } catch (ExecutionException ee) { t = ee.InnerException; } catch (InterruptedException ie) { Thread.CurrentThread.Interrupt(); // ignore/reset } } if (t != null) Console.WriteLine(t); } }
protected AfterExecute ( IRunnable runnable, Exception exception ) : void
runnable IRunnable The runnable that has completed.
exception System.Exception /// The exception that caused termination, or null if /// execution completed normally. ///
return void

AwaitTermination() public method

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
public AwaitTermination ( System.TimeSpan duration ) : bool
duration System.TimeSpan the time span to wait. ///
return bool

BeforeExecute() protected method

Method invoked prior to executing the given IRunnable in the given thread.
This method is invoked by thread that will execute runnable, and may be used to re-initialize ThreadLocals, or to perform logging. This implementation does nothing, but may be customized in subclasses. Note: To properly nest multiple overridings, subclasses should generally invoke base.BeforeExecute at the end of this method.
protected BeforeExecute ( System.Thread thread, IRunnable runnable ) : void
thread System.Thread the thread that will run .
runnable IRunnable the task that will be executed.
return void

Dispose() public method

Shutsdown and disposes of this ThreadPoolExecutor.
public Dispose ( ) : void
return void

Dispose() protected method

Helper method to dispose of this ThreadPoolExecutor
protected Dispose ( bool disposing ) : void
disposing bool true if being called from , /// false if being called from finalizer.
return void

DoExecute() protected method

Executes the given task sometime in the future. The task may execute in a new thread or in an existing pooled thread.
If the task cannot be submitted for execution, either because this executor has been shutdown or because its capacity has been reached, the task is handled by the current IRejectedExecutionHandler for this ThreadPoolExecutor.
/// if the task cannot be accepted. /// /// if is null ///
protected DoExecute ( IRunnable command ) : void
command IRunnable the task to execute
return void

OnShutdown() protected method

Performs any further cleanup following run state transition on invocation of shutdown. A no-op here, but used by ScheduledThreadPoolExecutor to cancel delayed tasks.
protected OnShutdown ( ) : void
return void

PreStartAllCoreThreads() public method

Starts all core threads, causing them to idly wait for work.
This overrides the default policy of starting core threads only when new tasks are executed.
public PreStartAllCoreThreads ( ) : int
return int

PreStartCoreThread() public method

Starts a core thread, causing it to idly wait for work. This overrides the default policy of starting core threads only when new tasks are executed. This method will return false if all core threads have already been started.
public PreStartCoreThread ( ) : bool
return bool

Purge() public method

Tries to remove from the work queue all IFuture{T} tasks that have been cancelled. This method can be useful as a storage reclamation operation, that has no other impact on functionality. Cancelled tasks are never executed, but may accumulate in work queues until worker threads can actively remove them. Invoking this method instead tries to remove them now. However, this method may fail to remove tasks in the presence of interference by other threads.
public Purge ( ) : void
return void

Remove() public method

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.
This method may be useful as one part of a cancellation scheme. It may fail to remove tasks that have been converted into other forms before being placed on the internal queue. For example, a task entered using IExecutorService.Submit(Action) might be converted into a form that maintains IFuture{T} status. However, in such cases, method Purge may be used to remove those Futures that have been cancelled.
public Remove ( System.Action task ) : bool
task System.Action The task to remove.
return bool

Remove() public method

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.
This method may be useful as one part of a cancellation scheme. It may fail to remove tasks that have been converted into other forms before being placed on the internal queue. For example, a task entered using IExecutorService.Submit(Action) might be converted into a form that maintains IFuture{T} status. However, in such cases, method Purge may be used to remove those Futures that have been cancelled.
public Remove ( IRunnable task ) : bool
task IRunnable The task to remove.
return bool

Shutdown() public method

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.
public Shutdown ( ) : void
return void

ShutdownNow() public method

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution. These tasks are drained (removed) from the task queue upon return from this method.

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. This implementation cancels tasks via Thread.Interrupt, so any task that fails to respond to interrupts may never terminate.

public ShutdownNow ( ) : IList
return IList

Terminated() protected method

Method invoked when the IExecutor has terminated. Default implementation does nothing.

Note: To properly nest multiple overridings, subclasses should generally invoke base.terminated within this method.

protected Terminated ( ) : void
return void

ThreadPoolExecutor() public method

Creates a new ThreadPoolExecutor with the given initial parameters and default thread factory and rejected execution handler.
> It may be more convenient to use one of the Executors factory methods instead of this general purpose constructor.
/// If or is less than zero, or if /// is less than or equal to zero, or if is greater than /// if is null
public ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, System.TimeSpan keepAliveTime, IBlockingQueue workQueue ) : System
corePoolSize int the number of threads to keep in the pool, even if they are idle.
maximumPoolSize int the maximum number of threads to allow in the pool.
keepAliveTime System.TimeSpan /// When the number of threads is greater than /// , this is the maximum time that excess idle threads /// will wait for new tasks before terminating. ///
workQueue IBlockingQueue /// The queue to use for holding tasks before they /// are executed. This queue will hold only the /// tasks submitted by the method. ///
return System

ThreadPoolExecutor() public method

Creates a new ThreadPoolExecutor with the given initial parameters and IThreadFactory. Creates a new ThreadPoolExecutor with the given initial parameters and default RejectedExecutionException.
/// If or is less than zero, or if /// is less than or equal to zero, or if is greater than /// if or is null
public ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, System.TimeSpan keepAliveTime, IBlockingQueue workQueue, IRejectedExecutionHandler handler ) : System
corePoolSize int the number of threads to keep in the pool, even if they are idle.
maximumPoolSize int the maximum number of threads to allow in the pool.
keepAliveTime System.TimeSpan /// When the number of threads is greater than /// , this is the maximum time that excess idle threads /// will wait for new tasks before terminating. ///
workQueue IBlockingQueue /// The queue to use for holding tasks before they /// are executed. This queue will hold only the /// tasks submitted by the method. ///
handler IRejectedExecutionHandler /// The to use when execution is blocked /// because the thread bounds and queue capacities are reached. ///
return System

ThreadPoolExecutor() public method

Creates a new ThreadPoolExecutor with the given initial parameters and default RejectedExecutionException.
/// If or is less than zero, or if /// is less than or equal to zero, or if is greater than /// if or is null
public ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, System.TimeSpan keepAliveTime, IBlockingQueue workQueue, IThreadFactory threadFactory ) : System
corePoolSize int the number of threads to keep in the pool, even if they are idle.
maximumPoolSize int the maximum number of threads to allow in the pool.
keepAliveTime System.TimeSpan /// When the number of threads is greater than /// , this is the maximum time that excess idle threads /// will wait for new tasks before terminating. ///
workQueue IBlockingQueue /// The queue to use for holding tasks before they /// are executed. This queue will hold only the /// tasks submitted by the method. ///
threadFactory IThreadFactory /// to use for new thread creation. ///
return System

ThreadPoolExecutor() public method

Creates a new ThreadPoolExecutor with the given initial parameters.
/// If or is less than zero, or if /// is less than or equal to zero, or if is greater than /// if , , or is null
public ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize, System.TimeSpan keepAliveTime, IBlockingQueue workQueue, IThreadFactory threadFactory, IRejectedExecutionHandler handler ) : System
corePoolSize int the number of threads to keep in the pool, even if they are idle.
maximumPoolSize int the maximum number of threads to allow in the pool.
keepAliveTime System.TimeSpan /// When the number of threads is greater than /// , this is the maximum time that excess idle threads /// will wait for new tasks before terminating. ///
workQueue IBlockingQueue /// The queue to use for holding tasks before they /// are executed. This queue will hold only the /// tasks submitted by the method. ///
threadFactory IThreadFactory /// to use for new thread creation. ///
handler IRejectedExecutionHandler /// The to use when execution is blocked /// because the thread bounds and queue capacities are reached. ///
return System