Top Description Fields Constructors Methods
org.springframework.scheduling.concurrent

public Class ThreadPoolTaskExecutor

extends ExecutorConfigurationSupport
implements AsyncListenableTaskExecutor, SchedulingTaskExecutor
Class Inheritance
All Implemented Interfaces
org.springframework.scheduling.SchedulingTaskExecutor, org.springframework.core.task.AsyncTaskExecutor, org.springframework.core.task.TaskExecutor, java.util.concurrent.Executor, org.springframework.core.task.AsyncListenableTaskExecutor
Annotations
@SuppressWarnings:serial, deprecation
Imports
java.util.Map, java.util.concurrent.BlockingQueue, .Callable, .Executor, .ExecutorService, .Future, .LinkedBlockingQueue, .RejectedExecutionException, .RejectedExecutionHandler, .SynchronousQueue, .ThreadFactory, .ThreadPoolExecutor, .TimeUnit, org.springframework.core.task.AsyncListenableTaskExecutor, .TaskDecorator, .TaskRejectedException, org.springframework.lang.Nullable, org.springframework.scheduling.SchedulingTaskExecutor, org.springframework.util.Assert, .ConcurrentReferenceHashMap, org.springframework.util.concurrent.ListenableFuture, .ListenableFutureTask

References Deprecated

AsyncListenableTaskExecutor is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

JavaBean that allows for configuring a java.util.concurrent.ThreadPoolExecutor in bean style (through its "corePoolSize", "maxPoolSize", "keepAliveSeconds", "queueCapacity" properties) and exposing it as a Spring org.springframework.core.task.TaskExecutor. This class is also well suited for management and monitoring (e.g. through JMX), providing several useful attributes: "corePoolSize", "maxPoolSize", "keepAliveSeconds" (all supporting updates at runtime); "poolSize", "activeCount" (for introspection only).

The default configuration is a core pool size of 1, with unlimited max pool size and unlimited queue capacity. This is roughly equivalent to java.util.concurrent.Executors#newSingleThreadExecutor(), sharing a single thread for all tasks. Setting "queueCapacity" to 0 mimics java.util.concurrent.Executors#newCachedThreadPool(), with immediate scaling of threads in the pool to a potentially very high number. Consider also setting a "maxPoolSize" at that point, as well as possibly a higher "corePoolSize" (see also the "allowCoreThreadTimeOut" mode of scaling).

Note

This class implements Spring's org.springframework.core.task.TaskExecutor interface as well as the java.util.concurrent.Executor interface, with the former being the primary interface, the other just serving as secondary convenience. For this reason, the exception handling follows the TaskExecutor contract rather than the Executor contract, in particular regarding the org.springframework.core.task.TaskRejectedException.

For an alternative, you may set up a ThreadPoolExecutor instance directly using constructor injection, or use a factory method definition that points to the java.util.concurrent.Executors class. To expose such a raw Executor as a Spring org.springframework.core.task.TaskExecutor, simply wrap it with a org.springframework.scheduling.concurrent.ConcurrentTaskExecutor adapter.

Authors
Juergen Hoeller, Rémy Guihard, Sam Brannen
Since
2.0
See Also
org.springframework.core.task.TaskExecutor, java.util.concurrent.ThreadPoolExecutor, ThreadPoolExecutorFactoryBean, ConcurrentTaskExecutor

Field Summary

Modifier and TypeField and Description
private boolean
private int
private final Map<Runnable, Object>
private int
private int
private final Object
private boolean
private int
private boolean
private TaskDecorator
private ThreadPoolExecutor
Inherited from org.springframework.scheduling.concurrent.ExecutorConfigurationSupport:
logger

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
protected void
cancelRemainingTask(Runnable
the task to cancel (typically a RunnableFuture)
task
)

Overrides org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.cancelRemainingTask.

Cancel the given remaining task which never commenced execution, as returned from ExecutorService#shutdownNow().

protected BlockingQueue<Runnable>

Returns:

the BlockingQueue instance
createQueue
(int
the specified queue capacity
queueCapacity
)

Create the BlockingQueue to use for the ThreadPoolExecutor.

public void
execute(Runnable
the Runnable to execute (never null)
task
)

Implements org.springframework.core.task.TaskExecutor.execute.

Execute the given task.

public int
getActiveCount()

Return the number of currently active threads.

public int
getCorePoolSize()

Return the ThreadPoolExecutor's core pool size.

public int
getKeepAliveSeconds()

Return the ThreadPoolExecutor's keep-alive seconds.

public int
getMaxPoolSize()

Return the ThreadPoolExecutor's maximum pool size.

public int
getPoolSize()

Return the current pool size.

public int
getQueueCapacity()

Return the capacity for the ThreadPoolExecutor's BlockingQueue.

public int
getQueueSize()

Return the current queue size.

public ThreadPoolExecutor

Returns:

the underlying ThreadPoolExecutor (never null)
getThreadPoolExecutor
()

Return the underlying ThreadPoolExecutor for native access.

protected ExecutorService
initializeExecutor(ThreadFactory
the ThreadFactory to use
threadFactory
,
RejectedExecutionHandler
the RejectedExecutionHandler to use
rejectedExecutionHandler
)

Implements abstract org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.initializeExecutor.

Note

This method exposes an ExecutorService to its base class but stores the actual ThreadPoolExecutor handle internally.

protected void
initiateEarlyShutdown()

Overrides org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.initiateEarlyShutdown.

Early shutdown signal: do not trigger further tasks, let existing tasks complete before hitting the actual destruction step in the shutdown() method.

public void
setAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut)

Specify whether to allow core threads to time out.

public void
setCorePoolSize(int corePoolSize)

Set the ThreadPoolExecutor's core pool size.

public void
setKeepAliveSeconds(int keepAliveSeconds)

Set the ThreadPoolExecutor's keep-alive seconds.

public void
setMaxPoolSize(int maxPoolSize)

Set the ThreadPoolExecutor's maximum pool size.

public void
setPrestartAllCoreThreads(boolean prestartAllCoreThreads)

Specify whether to start all core threads, causing them to idly wait for work.

public void
setQueueCapacity(int queueCapacity)

Set the capacity for the ThreadPoolExecutor's BlockingQueue.

public void
setStrictEarlyShutdown(boolean defaultEarlyShutdown)

Specify whether to initiate an early shutdown signal on context close, disposing all idle threads and rejecting further task submissions.

public void
setTaskDecorator(TaskDecorator taskDecorator)

Specify a custom TaskDecorator to be applied to any Runnable about to be executed.

public Future<?>
submit(Runnable
the Runnable to execute (never null)
task
)

Overrides default org.springframework.core.task.AsyncTaskExecutor.submit.

Submit a Runnable task for execution, receiving a Future representing that task.

public <T> Future<T>
submit(Callable<T>
the Callable to execute (never null)
task
)

Overrides default org.springframework.core.task.AsyncTaskExecutor.submit.

Submit a Callable task for execution, receiving a Future representing that task.

public ListenableFuture<?>
submitListenable(Runnable
the Runnable to execute (never null)
task
)

Implements org.springframework.core.task.AsyncListenableTaskExecutor.submitListenable.

References Deprecated ListenableFuture is deprecated or references (maybe indirectly) at least one deprecated element.

Submit a Runnable task for execution, receiving a ListenableFuture representing that task.

public <T> ListenableFuture<T>
submitListenable(Callable<T>
the Callable to execute (never null)
task
)

Implements org.springframework.core.task.AsyncListenableTaskExecutor.submitListenable.

References Deprecated ListenableFuture is deprecated or references (maybe indirectly) at least one deprecated element.

Submit a Callable task for execution, receiving a ListenableFuture representing that task.

Inherited from org.springframework.scheduling.concurrent.ExecutorConfigurationSupport:
afterExecuteafterPropertiesSetbeforeExecutedestroygetPhaseinitializeinitiateShutdownisRunningonApplicationEventsetAcceptTasksAfterContextClosesetApplicationContextsetAwaitTerminationMillissetAwaitTerminationSecondssetBeanNamesetPhasesetRejectedExecutionHandlersetThreadFactorysetThreadNamePrefixsetWaitForTasksToCompleteOnShutdownshutdownstartstopstop

Field Detail

allowCoreThreadTimeOutback to summary
private boolean allowCoreThreadTimeOut
corePoolSizeback to summary
private int corePoolSize
decoratedTaskMapback to summary
private final Map<Runnable, Object> decoratedTaskMap
keepAliveSecondsback to summary
private int keepAliveSeconds
maxPoolSizeback to summary
private int maxPoolSize
poolSizeMonitorback to summary
private final Object poolSizeMonitor
prestartAllCoreThreadsback to summary
private boolean prestartAllCoreThreads
queueCapacityback to summary
private int queueCapacity
strictEarlyShutdownback to summary
private boolean strictEarlyShutdown
taskDecoratorback to summary
private TaskDecorator taskDecorator
Annotations
@Nullable
threadPoolExecutorback to summary
private ThreadPoolExecutor threadPoolExecutor
Annotations
@Nullable

Constructor Detail

ThreadPoolTaskExecutorback to summary
public ThreadPoolTaskExecutor()

Method Detail

cancelRemainingTaskback to summary
protected void cancelRemainingTask(Runnable task)

Overrides org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.cancelRemainingTask.

Doc from org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.cancelRemainingTask.

Cancel the given remaining task which never commenced execution, as returned from ExecutorService#shutdownNow().

Parameters
task:Runnable

the task to cancel (typically a RunnableFuture)

Annotations
@Override
createQueueback to summary
protected BlockingQueue<Runnable> createQueue(int queueCapacity)

Create the BlockingQueue to use for the ThreadPoolExecutor.

A LinkedBlockingQueue instance will be created for a positive capacity value; a SynchronousQueue otherwise.

Parameters
queueCapacity:int

the specified queue capacity

Returns:BlockingQueue<Runnable>

the BlockingQueue instance

See Also
java.util.concurrent.LinkedBlockingQueue, java.util.concurrent.SynchronousQueue
executeback to summary
public void execute(Runnable task)

Implements org.springframework.core.task.TaskExecutor.execute.

Doc from org.springframework.core.task.TaskExecutor.execute.

Execute the given task.

The call might return immediately if the implementation uses an asynchronous execution strategy, or might block in the case of synchronous execution.

Parameters
task:Runnable

the Runnable to execute (never null)

Annotations
@Override
getActiveCountback to summary
public int getActiveCount()

Return the number of currently active threads.

See Also
java.util.concurrent.ThreadPoolExecutor#getActiveCount()
getCorePoolSizeback to summary
public int getCorePoolSize()

Return the ThreadPoolExecutor's core pool size.

getKeepAliveSecondsback to summary
public int getKeepAliveSeconds()

Return the ThreadPoolExecutor's keep-alive seconds.

getMaxPoolSizeback to summary
public int getMaxPoolSize()

Return the ThreadPoolExecutor's maximum pool size.

getPoolSizeback to summary
public int getPoolSize()

Return the current pool size.

See Also
java.util.concurrent.ThreadPoolExecutor#getPoolSize()
getQueueCapacityback to summary
public int getQueueCapacity()

Return the capacity for the ThreadPoolExecutor's BlockingQueue.

Since
5.3.21
See Also
setQueueCapacity(int)
getQueueSizeback to summary
public int getQueueSize()

Return the current queue size.

Since
5.3.21
See Also
java.util.concurrent.ThreadPoolExecutor#getQueue()
getThreadPoolExecutorback to summary
public ThreadPoolExecutor getThreadPoolExecutor() throws IllegalStateException

Return the underlying ThreadPoolExecutor for native access.

Returns:ThreadPoolExecutor

the underlying ThreadPoolExecutor (never null)

Exceptions
IllegalStateException:
if the ThreadPoolTaskExecutor hasn't been initialized yet
initializeExecutorback to summary
protected ExecutorService initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler)

Implements abstract org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.initializeExecutor.

Note

This method exposes an ExecutorService to its base class but stores the actual ThreadPoolExecutor handle internally. Do not override this method for replacing the executor, rather just for decorating its ExecutorService handle or storing custom state.

Parameters
threadFactory:ThreadFactory

Doc from org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.initializeExecutor.

the ThreadFactory to use

rejectedExecutionHandler:RejectedExecutionHandler

Doc from org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.initializeExecutor.

the RejectedExecutionHandler to use

Returns:ExecutorService

Doc from org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.initializeExecutor.

a new ExecutorService instance

Annotations
@Override
initiateEarlyShutdownback to summary
protected void initiateEarlyShutdown()

Overrides org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.initiateEarlyShutdown.

Doc from org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.initiateEarlyShutdown.

Early shutdown signal: do not trigger further tasks, let existing tasks complete before hitting the actual destruction step in the shutdown() method. This goes along with a coordinated lifecycle stop phase.

Called from onApplicationEvent(ContextClosedEvent) if no indications for a late shutdown have been determined, that is, if the "acceptTasksAfterContextClose and "waitForTasksToCompleteOnShutdown" flags have not been set.

The default implementation calls initiateShutdown().

Annotations
@Override
setAllowCoreThreadTimeOutback to summary
public void setAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut)

Specify whether to allow core threads to time out. This enables dynamic growing and shrinking even in combination with a non-zero queue (since the max pool size will only grow once the queue is full).

Default is "false".

See Also
java.util.concurrent.ThreadPoolExecutor#allowCoreThreadTimeOut(boolean)
setCorePoolSizeback to summary
public void setCorePoolSize(int corePoolSize)

Set the ThreadPoolExecutor's core pool size. Default is 1.

This setting can be modified at runtime, for example through JMX.

setKeepAliveSecondsback to summary
public void setKeepAliveSeconds(int keepAliveSeconds)

Set the ThreadPoolExecutor's keep-alive seconds.

Default is 60.

This setting can be modified at runtime, for example through JMX.

setMaxPoolSizeback to summary
public void setMaxPoolSize(int maxPoolSize)

Set the ThreadPoolExecutor's maximum pool size. Default is Integer.MAX_VALUE.

This setting can be modified at runtime, for example through JMX.

setPrestartAllCoreThreadsback to summary
public void setPrestartAllCoreThreads(boolean prestartAllCoreThreads)

Specify whether to start all core threads, causing them to idly wait for work.

Default is "false", starting threads and adding them to the pool on demand.

Since
5.3.14
See Also
java.util.concurrent.ThreadPoolExecutor#prestartAllCoreThreads
setQueueCapacityback to summary
public void setQueueCapacity(int queueCapacity)

Set the capacity for the ThreadPoolExecutor's BlockingQueue.

Default is Integer.MAX_VALUE.

Any positive value will lead to a LinkedBlockingQueue instance; any other value will lead to a SynchronousQueue instance.

See Also
java.util.concurrent.LinkedBlockingQueue, java.util.concurrent.SynchronousQueue
setStrictEarlyShutdownback to summary
public void setStrictEarlyShutdown(boolean defaultEarlyShutdown)

Specify whether to initiate an early shutdown signal on context close, disposing all idle threads and rejecting further task submissions.

By default, existing tasks will be allowed to complete within the coordinated lifecycle stop phase in any case. This setting just controls whether an explicit ThreadPoolExecutor#shutdown() call will be triggered on context close, rejecting task submissions after that point.

As of 6.1.4, the default is "false", leniently allowing for late tasks to arrive after context close, still participating in the lifecycle stop phase. Note that this differs from setAcceptTasksAfterContextClose which completely bypasses the coordinated lifecycle stop phase, with no explicit waiting for the completion of existing tasks at all.

Switch this to "true" for a strict early shutdown signal analogous to the 6.1-established default behavior of ThreadPoolTaskScheduler. Note that the related flags setAcceptTasksAfterContextClose and setWaitForTasksToCompleteOnShutdown will override this setting, leading to a late shutdown without a coordinated lifecycle stop phase.

Since
6.1.4
See Also
initiateShutdown()
setTaskDecoratorback to summary
public void setTaskDecorator(TaskDecorator taskDecorator)

Specify a custom TaskDecorator to be applied to any Runnable about to be executed.

Note that such a decorator is not necessarily being applied to the user-supplied Runnable/Callable but rather to the actual execution callback (which may be a wrapper around the user-supplied task).

The primary use case is to set some execution context around the task's invocation, or to provide some monitoring/statistics for task execution.

Note

Exception handling in TaskDecorator implementations is limited to plain Runnable execution via execute calls. In case of #submit calls, the exposed Runnable will be a FutureTask which does not propagate any exceptions; you might have to cast it and call Future#get to evaluate exceptions. See the ThreadPoolExecutor#afterExecute javadoc for an example of how to access exceptions in such a Future case.

Since
4.3
submitback to summary
public Future<?> submit(Runnable task)

Overrides default org.springframework.core.task.AsyncTaskExecutor.submit.

Doc from org.springframework.core.task.AsyncTaskExecutor.submit.

Submit a Runnable task for execution, receiving a Future representing that task. The Future will return a null result upon completion.

As of 6.1, this method comes with a default implementation that delegates to execute(Runnable).

Parameters
task:Runnable

the Runnable to execute (never null)

Returns:Future<?>

a Future representing pending completion of the task

Annotations
@Override
submitback to summary
public <T> Future<T> submit(Callable<T> task)

Overrides default org.springframework.core.task.AsyncTaskExecutor.submit.

Doc from org.springframework.core.task.AsyncTaskExecutor.submit.

Submit a Callable task for execution, receiving a Future representing that task. The Future will return the Callable's result upon completion.

As of 6.1, this method comes with a default implementation that delegates to execute(Runnable).

Parameters
task:Callable<T>

the Callable to execute (never null)

Returns:Future<T>

a Future representing pending completion of the task

Annotations
@Override
submitListenableback to summary
public ListenableFuture<?> submitListenable(Runnable task)

Implements org.springframework.core.task.AsyncListenableTaskExecutor.submitListenable.

Doc from org.springframework.core.task.AsyncListenableTaskExecutor.submitListenable.

References Deprecated

ListenableFuture is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Submit a Runnable task for execution, receiving a ListenableFuture representing that task. The Future will return a null result upon completion.

Parameters
task:Runnable

the Runnable to execute (never null)

Returns:ListenableFuture<?>

a ListenableFuture representing pending completion of the task

Annotations
@Override
submitListenableback to summary
public <T> ListenableFuture<T> submitListenable(Callable<T> task)

Implements org.springframework.core.task.AsyncListenableTaskExecutor.submitListenable.

Doc from org.springframework.core.task.AsyncListenableTaskExecutor.submitListenable.

References Deprecated

ListenableFuture is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Submit a Callable task for execution, receiving a ListenableFuture representing that task. The Future will return the Callable's result upon completion.

Parameters
task:Callable<T>

the Callable to execute (never null)

Returns:ListenableFuture<T>

a ListenableFuture representing pending completion of the task

Annotations
@Override