Class ThreadPoolTaskExecutor
- java.lang.Object
- org.springframework.util.CustomizableThreadCreator
- org.springframework.scheduling.concurrent.CustomizableThreadFactory
- org.springframework.scheduling.concurrent.ExecutorConfigurationSupport
- org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
- All Implemented Interfaces:
Serializable,Executor,ThreadFactory,Aware,BeanNameAware,DisposableBean,InitializingBean,AsyncListenableTaskExecutor,AsyncTaskExecutor,TaskExecutor,SchedulingTaskExecutor
public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport implements AsyncListenableTaskExecutor, SchedulingTaskExecutor
JavaBean that allows for configuring aThreadPoolExecutorin bean style (through its "corePoolSize", "maxPoolSize", "keepAliveSeconds", "queueCapacity" properties) and exposing it as a SpringTaskExecutor. 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
Executors.newSingleThreadExecutor(), sharing a single thread for all tasks. Setting"queueCapacity"to 0 mimicsExecutors.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
TaskExecutorinterface as well as theExecutorinterface, 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 theTaskRejectedException.For an alternative, you may set up a ThreadPoolExecutor instance directly using constructor injection, or use a factory method definition that points to the
Executorsclass. To expose such a raw Executor as a SpringTaskExecutor, simply wrap it with aConcurrentTaskExecutoradapter.- Since:
- 2.0
- Author:
- Juergen Hoeller
- See Also:
TaskExecutor,ThreadPoolExecutor,ThreadPoolExecutorFactoryBean,ConcurrentTaskExecutor, Serialized Form
Field Summary
Fields inherited from class org.springframework.scheduling.concurrent.ExecutorConfigurationSupport
logger
Fields inherited from interface org.springframework.core.task.AsyncTaskExecutor
TIMEOUT_IMMEDIATE, TIMEOUT_INDEFINITE
Constructor Summary
Constructors Constructor Description ThreadPoolTaskExecutor()
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description protected BlockingQueue<Runnable>createQueue(int queueCapacity)Create the BlockingQueue to use for the ThreadPoolExecutor.voidexecute(Runnable task)Execute the giventask.voidexecute(Runnable task, long startTimeout)Execute the giventask.intgetActiveCount()Return the number of currently active threads.intgetCorePoolSize()Return the ThreadPoolExecutor's core pool size.intgetKeepAliveSeconds()Return the ThreadPoolExecutor's keep-alive seconds.intgetMaxPoolSize()Return the ThreadPoolExecutor's maximum pool size.intgetPoolSize()Return the current pool size.ThreadPoolExecutorgetThreadPoolExecutor()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.booleanprefersShortLivedTasks()This task executor prefers short-lived work units.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.voidsetQueueCapacity(int queueCapacity)Set the capacity for the ThreadPoolExecutor's BlockingQueue.voidsetTaskDecorator(TaskDecorator taskDecorator)Specify a customTaskDecoratorto be applied to anyRunnableabout to be executed.Future<?>submit(Runnable task)Submit a Runnable task for execution, receiving a Future representing that task.<T> Future<T>submit(Callable<T> task)Submit a Callable task for execution, receiving a Future representing that task.ListenableFuture<?>submitListenable(Runnable task)Submit aRunnabletask for execution, receiving aListenableFuturerepresenting that task.<T> ListenableFuture<T>submitListenable(Callable<T> task)Submit aCallabletask for execution, receiving aListenableFuturerepresenting that task.Methods inherited from class org.springframework.scheduling.concurrent.ExecutorConfigurationSupport
afterPropertiesSet, destroy, initialize, setAwaitTerminationSeconds, setBeanName, setRejectedExecutionHandler, setThreadFactory, setThreadNamePrefix, setWaitForTasksToCompleteOnShutdown, shutdown
Methods inherited from class org.springframework.scheduling.concurrent.CustomizableThreadFactory
newThread
Methods inherited from class org.springframework.util.CustomizableThreadCreator
createThread, getDefaultThreadNamePrefix, getThreadGroup, getThreadNamePrefix, getThreadPriority, isDaemon, nextThreadName, setDaemon, setThreadGroup, setThreadGroupName, setThreadPriority
Constructor Detail
ThreadPoolTaskExecutor
public ThreadPoolTaskExecutor()
Method Detail
setCorePoolSize
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.
getCorePoolSize
public int getCorePoolSize()
Return the ThreadPoolExecutor's core pool size.
setMaxPoolSize
public 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.
getMaxPoolSize
public int getMaxPoolSize()
Return the ThreadPoolExecutor's maximum pool size.
setKeepAliveSeconds
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.
getKeepAliveSeconds
public int getKeepAliveSeconds()
Return the ThreadPoolExecutor's keep-alive seconds.
setQueueCapacity
public void setQueueCapacity(int queueCapacity)
Set the capacity for the ThreadPoolExecutor's BlockingQueue. Default isInteger.MAX_VALUE.Any positive value will lead to a LinkedBlockingQueue instance; any other value will lead to a SynchronousQueue instance.
- See Also:
LinkedBlockingQueue,SynchronousQueue
setAllowCoreThreadTimeOut
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".
setTaskDecorator
public void setTaskDecorator(TaskDecorator taskDecorator)
Specify 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
initializeExecutor
protected 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 classExecutorConfigurationSupport- Parameters:
threadFactory- the ThreadFactory to userejectedExecutionHandler- the RejectedExecutionHandler to use- Returns:
- a new ExecutorService instance
- See Also:
ExecutorConfigurationSupport.afterPropertiesSet()
createQueue
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 else.
- Parameters:
queueCapacity- the specified queue capacity- Returns:
- the BlockingQueue instance
- See Also:
LinkedBlockingQueue,SynchronousQueue
getThreadPoolExecutor
public ThreadPoolExecutor getThreadPoolExecutor() throws IllegalStateException
Return the underlying ThreadPoolExecutor for native access.- Returns:
- the underlying ThreadPoolExecutor (never
null) - Throws:
IllegalStateException- if the ThreadPoolTaskExecutor hasn't been initialized yet
getPoolSize
public int getPoolSize()
Return the current pool size.- See Also:
ThreadPoolExecutor.getPoolSize()
getActiveCount
public int getActiveCount()
Return the number of currently active threads.- See Also:
ThreadPoolExecutor.getActiveCount()
execute
public void execute(Runnable task)
Description 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 interfaceExecutor- Specified by:
executein interfaceTaskExecutor- Parameters:
task- theRunnableto execute (nevernull)
execute
public void execute(Runnable task, long startTimeout)
Description copied from interface:AsyncTaskExecutorExecute the giventask.- Specified by:
executein interfaceAsyncTaskExecutor- Parameters:
task- theRunnableto execute (nevernull)startTimeout- the time duration (milliseconds) within which the task is supposed to start. This is intended as a hint to the executor, allowing for preferred handling of immediate tasks. Typical values areAsyncTaskExecutor.TIMEOUT_IMMEDIATEorAsyncTaskExecutor.TIMEOUT_INDEFINITE(the default as used byTaskExecutor.execute(Runnable)).
submit
public Future<?> submit(Runnable task)
Description copied from interface:AsyncTaskExecutorSubmit a Runnable task for execution, receiving a Future representing that task. The Future will return anullresult upon completion.- Specified by:
submitin interfaceAsyncTaskExecutor- Parameters:
task- theRunnableto execute (nevernull)- Returns:
- a Future representing pending completion of the task
submit
public <T> Future<T> submit(Callable<T> task)
Description 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.- Specified by:
submitin interfaceAsyncTaskExecutor- Parameters:
task- theCallableto execute (nevernull)- Returns:
- a Future representing pending completion of the task
submitListenable
public ListenableFuture<?> submitListenable(Runnable task)
Description copied from interface:AsyncListenableTaskExecutorSubmit aRunnabletask for execution, receiving aListenableFuturerepresenting that task. The Future will return anullresult upon completion.- Specified by:
submitListenablein interfaceAsyncListenableTaskExecutor- Parameters:
task- theRunnableto execute (nevernull)- Returns:
- a
ListenableFuturerepresenting pending completion of the task
submitListenable
public <T> ListenableFuture<T> submitListenable(Callable<T> task)
Description copied from interface:AsyncListenableTaskExecutorSubmit aCallabletask for execution, receiving aListenableFuturerepresenting that task. The Future will return the Callable's result upon completion.- Specified by:
submitListenablein interfaceAsyncListenableTaskExecutor- Parameters:
task- theCallableto execute (nevernull)- Returns:
- a
ListenableFuturerepresenting pending completion of the task
prefersShortLivedTasks
public boolean prefersShortLivedTasks()
This task executor prefers short-lived work units.- Specified by:
prefersShortLivedTasksin interfaceSchedulingTaskExecutor- Returns:
trueif thisTaskExecutorprefers short-lived tasks