Class ThreadPoolTaskExecutor
- All Implemented Interfaces:
- Serializable, Executor, ThreadFactory, EventListener, Aware, BeanNameAware, DisposableBean, InitializingBean, ApplicationContextAware, ApplicationListener<ContextClosedEvent>, Lifecycle, Phased, SmartLifecycle, AsyncTaskExecutor, TaskExecutor, SchedulingTaskExecutor
ThreadPoolExecutor
in bean style (through its "corePoolSize", "maxPoolSize", "keepAliveSeconds", "queueCapacity"
properties) and exposing it as a Spring TaskExecutor.
This class is also well suited for management and monitoring (for example, 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
Executors.newSingleThreadExecutor(), sharing a single
thread for all tasks. Setting "queueCapacity" to 0 mimics
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
TaskExecutor interface as well as the
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 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
Executors class. To expose such a raw Executor as a
Spring TaskExecutor, simply wrap it with a
ConcurrentTaskExecutor adapter.
- Since:
- 2.0
- Author:
- Juergen Hoeller, Rémy Guihard, Sam Brannen
- See Also:
- 
Field SummaryFields inherited from class ExecutorConfigurationSupportDEFAULT_PHASE, loggerFields inherited from interface AsyncTaskExecutorTIMEOUT_IMMEDIATE, TIMEOUT_INDEFINITE
- 
Constructor SummaryConstructors
- 
Method SummaryModifier and TypeMethodDescriptionprotected voidcancelRemainingTask(Runnable task) Cancel the given remaining task which never commenced execution, as returned fromExecutorService.shutdownNow().protected BlockingQueue<Runnable> createQueue(int queueCapacity) Create the BlockingQueue to use for the ThreadPoolExecutor.voidExecute the giventask.intReturn the number of currently active threads.intReturn the ThreadPoolExecutor's core pool size.intReturn the ThreadPoolExecutor's keep-alive seconds.intReturn the ThreadPoolExecutor's maximum pool size.intReturn the current pool size.intReturn the capacity for the ThreadPoolExecutor's BlockingQueue.intReturn the current queue size.Return the underlying ThreadPoolExecutor for native access.protected ExecutorServiceinitializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) Note: This method exposes anExecutorServiceto its base class but stores the actualThreadPoolExecutorhandle internally.protected voidEarly shutdown signal: do not trigger further tasks, let existing tasks complete before hitting the actual destruction step in theExecutorConfigurationSupport.shutdown()method.voidsetAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut) Specify whether to allow core threads to time out.voidsetCorePoolSize(int corePoolSize) Set the ThreadPoolExecutor's core pool size.voidsetKeepAliveSeconds(int keepAliveSeconds) Set the ThreadPoolExecutor's keep-alive seconds.voidsetMaxPoolSize(int maxPoolSize) Set the ThreadPoolExecutor's maximum pool size.voidsetPrestartAllCoreThreads(boolean prestartAllCoreThreads) Specify whether to start all core threads, causing them to idly wait for work.voidsetQueueCapacity(int queueCapacity) Set the capacity for the ThreadPoolExecutor's BlockingQueue.voidsetStrictEarlyShutdown(boolean defaultEarlyShutdown) Specify whether to initiate an early shutdown signal on context close, disposing all idle threads and rejecting further task submissions.voidsetTaskDecorator(TaskDecorator taskDecorator) Specify a customTaskDecoratorto be applied to anyRunnableabout to be executed.Future<?> Submit a Runnable task for execution, receiving a Future representing that task.<T> Future<T> Submit a Callable task for execution, receiving a Future representing that task.Methods inherited from class ExecutorConfigurationSupportafterExecute, afterPropertiesSet, beforeExecute, destroy, getPhase, initialize, initiateShutdown, isRunning, onApplicationEvent, setAcceptTasksAfterContextClose, setApplicationContext, setAwaitTerminationMillis, setAwaitTerminationSeconds, setBeanName, setPhase, setRejectedExecutionHandler, setThreadFactory, setThreadNamePrefix, setVirtualThreads, setWaitForTasksToCompleteOnShutdown, shutdown, start, stop, stopMethods inherited from class CustomizableThreadFactorynewThreadMethods inherited from class CustomizableThreadCreatorcreateThread, getDefaultThreadNamePrefix, getThreadGroup, getThreadNamePrefix, getThreadPriority, isDaemon, nextThreadName, setDaemon, setThreadGroup, setThreadGroupName, setThreadPriorityMethods inherited from class Objectclone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface ApplicationListenersupportsAsyncExecutionMethods inherited from interface AsyncTaskExecutorexecute, submitCompletable, submitCompletableMethods inherited from interface SchedulingTaskExecutorprefersShortLivedTasksMethods inherited from interface SmartLifecycleisAutoStartup, isPauseable
- 
Constructor Details- 
ThreadPoolTaskExecutorpublic ThreadPoolTaskExecutor()
 
- 
- 
Method Details- 
setCorePoolSizepublic 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. 
- 
getCorePoolSizepublic int getCorePoolSize()Return the ThreadPoolExecutor's core pool size.
- 
setMaxPoolSizepublic void setMaxPoolSize(int maxPoolSize) Set the ThreadPoolExecutor's maximum pool size. Default isInteger.MAX_VALUE.This setting can be modified at runtime, for example through JMX. 
- 
getMaxPoolSizepublic int getMaxPoolSize()Return the ThreadPoolExecutor's maximum pool size.
- 
setKeepAliveSecondspublic 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. 
- 
getKeepAliveSecondspublic int getKeepAliveSeconds()Return the ThreadPoolExecutor's keep-alive seconds.
- 
setQueueCapacitypublic 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:
 
- 
getQueueCapacitypublic int getQueueCapacity()Return the capacity for the ThreadPoolExecutor's BlockingQueue.- Since:
- 5.3.21
- See Also:
 
- 
setAllowCoreThreadTimeOutpublic 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:
 
- 
setPrestartAllCoreThreadspublic 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:
 
- 
setStrictEarlyShutdownpublic 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 ExecutorConfigurationSupport.setAcceptTasksAfterContextClose(boolean)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 flagsExecutorConfigurationSupport.setAcceptTasksAfterContextClose(boolean)andExecutorConfigurationSupport.setWaitForTasksToCompleteOnShutdown(boolean)will override this setting, leading to a late shutdown without a coordinated lifecycle stop phase.- Since:
- 6.1.4
- See Also:
 
- 
setTaskDecoratorSpecify a customTaskDecoratorto be applied to anyRunnableabout to be executed.Note that such a decorator is not necessarily being applied to the user-supplied Runnable/Callablebut 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 TaskDecoratorimplementations is limited to plainRunnableexecution viaexecutecalls. In case of#submitcalls, the exposedRunnablewill be aFutureTaskwhich does not propagate any exceptions; you might have to cast it and callFuture#getto evaluate exceptions. See theThreadPoolExecutor#afterExecutejavadoc for an example of how to access exceptions in such aFuturecase.- Since:
- 4.3
 
- 
initializeExecutorprotected ExecutorService initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) Note: This method exposes anExecutorServiceto its base class but stores the actualThreadPoolExecutorhandle internally. Do not override this method for replacing the executor, rather just for decorating itsExecutorServicehandle or storing custom state.- Specified by:
- initializeExecutorin class- ExecutorConfigurationSupport
- Parameters:
- threadFactory- the ThreadFactory to use
- rejectedExecutionHandler- the RejectedExecutionHandler to use
- Returns:
- a new ExecutorService instance
- See Also:
 
- 
createQueueCreate the BlockingQueue to use for the ThreadPoolExecutor.A LinkedBlockingQueue instance will be created for a positive capacity value; a SynchronousQueue otherwise. - Parameters:
- queueCapacity- the specified queue capacity
- Returns:
- the BlockingQueue instance
- See Also:
 
- 
getThreadPoolExecutorReturn the underlying ThreadPoolExecutor for native access.- Returns:
- the underlying ThreadPoolExecutor (never null)
- Throws:
- IllegalStateException- if the ThreadPoolTaskExecutor hasn't been initialized yet
 
- 
getPoolSizepublic int getPoolSize()Return the current pool size.- See Also:
 
- 
getQueueSizepublic int getQueueSize()Return the current queue size.- Since:
- 5.3.21
- See Also:
 
- 
getActiveCountpublic int getActiveCount()Return the number of currently active threads.- See Also:
 
- 
executeDescription copied from interface:TaskExecutorExecute the giventask.The call might return immediately if the implementation uses an asynchronous execution strategy, or might block in the case of synchronous execution. - Specified by:
- executein interface- Executor
- Specified by:
- executein interface- TaskExecutor
- Parameters:
- task- the- Runnableto execute (never- null)
 
- 
submitDescription copied from interface:AsyncTaskExecutorSubmit a Runnable task for execution, receiving a Future representing that task. The Future will return anullresult upon completion.As of 6.1, this method comes with a default implementation that delegates to TaskExecutor.execute(Runnable).- Specified by:
- submitin interface- AsyncTaskExecutor
- Parameters:
- task- the- Runnableto execute (never- null)
- Returns:
- a Future representing pending completion of the task
 
- 
submitDescription copied from interface:AsyncTaskExecutorSubmit 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 TaskExecutor.execute(Runnable).- Specified by:
- submitin interface- AsyncTaskExecutor
- Parameters:
- task- the- Callableto execute (never- null)
- Returns:
- a Future representing pending completion of the task
 
- 
cancelRemainingTaskDescription copied from class:ExecutorConfigurationSupportCancel the given remaining task which never commenced execution, as returned fromExecutorService.shutdownNow().- Overrides:
- cancelRemainingTaskin class- ExecutorConfigurationSupport
- Parameters:
- task- the task to cancel (typically a- RunnableFuture)
- See Also:
 
- 
initiateEarlyShutdownprotected void initiateEarlyShutdown()Description copied from class:ExecutorConfigurationSupportEarly shutdown signal: do not trigger further tasks, let existing tasks complete before hitting the actual destruction step in theExecutorConfigurationSupport.shutdown()method. This goes along with acoordinated lifecycle stop phase.Called from ExecutorConfigurationSupport.onApplicationEvent(ContextClosedEvent)if no indications for a late shutdown have been determined, that is, if the"acceptTasksAfterContextCloseand"waitForTasksToCompleteOnShutdown"flags have not been set.The default implementation calls ExecutorConfigurationSupport.initiateShutdown().- Overrides:
- initiateEarlyShutdownin class- ExecutorConfigurationSupport
- See Also:
 
 
-