org.springframework.scheduling.backportconcurrent
Class ThreadPoolTaskExecutor

java.lang.Object
  extended by org.springframework.util.CustomizableThreadCreator
      extended by org.springframework.scheduling.backportconcurrent.CustomizableThreadFactory
          extended by org.springframework.scheduling.backportconcurrent.ThreadPoolTaskExecutor
All Implemented Interfaces:
edu.emory.mathcs.backport.java.util.concurrent.Executor, edu.emory.mathcs.backport.java.util.concurrent.ThreadFactory, Serializable, BeanNameAware, DisposableBean, InitializingBean, AsyncTaskExecutor, TaskExecutor, SchedulingTaskExecutor

public class ThreadPoolTaskExecutor
extends CustomizableThreadFactory
implements SchedulingTaskExecutor, edu.emory.mathcs.backport.java.util.concurrent.Executor, BeanNameAware, InitializingBean, DisposableBean

JavaBean that allows for configuring a JSR-166 backport ThreadPoolExecutor in bean style (through its "corePoolSize", "maxPoolSize", "keepAliveSeconds", "queueCapacity" properties), exposing it as a Spring TaskExecutor. This is an alternative to configuring a ThreadPoolExecutor instance directly using constructor injection, with a separate ConcurrentTaskExecutor adapter wrapping it.

For any custom needs, in particular for defining a ScheduledThreadPoolExecutor, it is recommended to use a straight definition of the Executor instance or a factory method definition that points to the JSR-166 backport Executors class. To expose such a raw Executor as a Spring TaskExecutor, simply wrap it with a ConcurrentTaskExecutor adapter.

NOTE: This class implements Spring's TaskExecutor interface (and hence implicitly the standard Java 5 Executor interface) as well as the JSR-166 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 backport Executor contract, in particular regarding the TaskRejectedException.

Since:
2.0.3
Author:
Juergen Hoeller
See Also:
TaskExecutor, Executor, ThreadPoolExecutor, ScheduledThreadPoolExecutor, Executors, ConcurrentTaskExecutor, Serialized Form

Field Summary
protected  Log logger
           
 
Fields inherited from interface org.springframework.core.task.AsyncTaskExecutor
TIMEOUT_IMMEDIATE, TIMEOUT_INDEFINITE
 
Constructor Summary
ThreadPoolTaskExecutor()
           
 
Method Summary
 void afterPropertiesSet()
          Calls initialize() after the container applied all property values.
protected  edu.emory.mathcs.backport.java.util.concurrent.BlockingQueue createQueue(int queueCapacity)
          Create the BlockingQueue to use for the ThreadPoolExecutor.
 void destroy()
          Calls shutdown when the BeanFactory destroys the task executor instance.
 void execute(Runnable task)
          Implementation of both the JSR-166 backport Executor interface and the Spring TaskExecutor interface, delegating to the ThreadPoolExecutor instance.
 void execute(Runnable task, long startTimeout)
          Execute the given task.
 int getActiveCount()
          Return the number of currently active threads.
 int getCorePoolSize()
          Return the ThreadPoolExecutor's core pool size.
 int getKeepAliveSeconds()
          Return the ThreadPoolExecutor's keep-alive seconds.
 int getMaxPoolSize()
          Return the ThreadPoolExecutor's maximum pool size.
 int getPoolSize()
          Return the current pool size.
 edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor getThreadPoolExecutor()
          Return the underlying ThreadPoolExecutor for native access.
 void initialize()
          Creates the BlockingQueue and the ThreadPoolExecutor.
 boolean prefersShortLivedTasks()
          This task executor prefers short-lived work units.
 void setAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut)
          Specify whether to allow core threads to time out.
 void setBeanName(String name)
          Set the name of the bean in the bean factory that created this bean.
 void setCorePoolSize(int corePoolSize)
          Set the ThreadPoolExecutor's core pool size.
 void setKeepAliveSeconds(int keepAliveSeconds)
          Set the ThreadPoolExecutor's keep-alive seconds.
 void setMaxPoolSize(int maxPoolSize)
          Set the ThreadPoolExecutor's maximum pool size.
 void setQueueCapacity(int queueCapacity)
          Set the capacity for the ThreadPoolExecutor's BlockingQueue.
 void setRejectedExecutionHandler(edu.emory.mathcs.backport.java.util.concurrent.RejectedExecutionHandler rejectedExecutionHandler)
          Set the RejectedExecutionHandler to use for the ThreadPoolExecutor.
 void setThreadFactory(edu.emory.mathcs.backport.java.util.concurrent.ThreadFactory threadFactory)
          Set the ThreadFactory to use for the ThreadPoolExecutor's thread pool.
 void setThreadNamePrefix(String threadNamePrefix)
          Specify the prefix to use for the names of newly created threads.
 void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown)
          Set whether to wait for scheduled tasks to complete on shutdown.
 void shutdown()
          Perform a shutdown on the ThreadPoolExecutor.
<T> Future<T>
submit(Callable<T> task)
          Submit a Callable task for execution, receiving a Future representing that task.
 Future<?> submit(Runnable task)
          Submit a Runnable task for execution, receiving a Future representing that task.
 
Methods inherited from class org.springframework.scheduling.backportconcurrent.CustomizableThreadFactory
newThread
 
Methods inherited from class org.springframework.util.CustomizableThreadCreator
createThread, getDefaultThreadNamePrefix, getThreadGroup, getThreadNamePrefix, getThreadPriority, isDaemon, nextThreadName, setDaemon, setThreadGroup, setThreadGroupName, setThreadPriority
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

logger

protected final Log logger
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 is Integer.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.


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". Note that this feature is only available on backport-concurrent 3.0 or above (based on the code in Java 6).

See Also:
ThreadPoolExecutor.allowCoreThreadTimeOut(boolean)

setQueueCapacity

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:
LinkedBlockingQueue, SynchronousQueue

setThreadFactory

public void setThreadFactory(edu.emory.mathcs.backport.java.util.concurrent.ThreadFactory threadFactory)
Set the ThreadFactory to use for the ThreadPoolExecutor's thread pool.

Default is this executor itself (i.e. the factory that this executor inherits from). See CustomizableThreadCreator's javadoc for available bean properties.

See Also:
CustomizableThreadCreator.setThreadPriority(int), CustomizableThreadCreator.setDaemon(boolean)

setRejectedExecutionHandler

public void setRejectedExecutionHandler(edu.emory.mathcs.backport.java.util.concurrent.RejectedExecutionHandler rejectedExecutionHandler)
Set the RejectedExecutionHandler to use for the ThreadPoolExecutor. Default is the ThreadPoolExecutor's default abort policy.

See Also:
ThreadPoolExecutor.AbortPolicy

setWaitForTasksToCompleteOnShutdown

public void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown)
Set whether to wait for scheduled tasks to complete on shutdown.

Default is "false". Switch this to "true" if you prefer fully completed tasks at the expense of a longer shutdown phase.

See Also:
ThreadPoolExecutor.shutdown(), ThreadPoolExecutor.shutdownNow()

setThreadNamePrefix

public void setThreadNamePrefix(String threadNamePrefix)
Description copied from class: CustomizableThreadCreator
Specify the prefix to use for the names of newly created threads. Default is "SimpleAsyncTaskExecutor-".

Overrides:
setThreadNamePrefix in class CustomizableThreadCreator

setBeanName

public void setBeanName(String name)
Description copied from interface: BeanNameAware
Set the name of the bean in the bean factory that created this bean.

Invoked after population of normal bean properties but before an init callback such as InitializingBean.afterPropertiesSet() or a custom init-method.

Specified by:
setBeanName in interface BeanNameAware
Parameters:
name - the name of the bean in the factory. Note that this name is the actual bean name used in the factory, which may differ from the originally specified name: in particular for inner bean names, the actual bean name might have been made unique through appending "#..." suffixes. Use the BeanFactoryUtils.originalBeanName(String) method to extract the original bean name (without suffix), if desired.

afterPropertiesSet

public void afterPropertiesSet()
Calls initialize() after the container applied all property values.

Specified by:
afterPropertiesSet in interface InitializingBean
See Also:
initialize()

initialize

public void initialize()
Creates the BlockingQueue and the ThreadPoolExecutor.

See Also:
createQueue(int)

createQueue

protected edu.emory.mathcs.backport.java.util.concurrent.BlockingQueue 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 edu.emory.mathcs.backport.java.util.concurrent.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

execute

public void execute(Runnable task)
Implementation of both the JSR-166 backport Executor interface and the Spring TaskExecutor interface, delegating to the ThreadPoolExecutor instance.

Specified by:
execute in interface edu.emory.mathcs.backport.java.util.concurrent.Executor
Specified by:
execute in interface TaskExecutor
Parameters:
task - the Runnable to execute (never null)
See Also:
Executor.execute(Runnable), TaskExecutor.execute(Runnable)

execute

public void execute(Runnable task,
                    long startTimeout)
Description copied from interface: AsyncTaskExecutor
Execute the given task.

Specified by:
execute in interface AsyncTaskExecutor
Parameters:
task - the Runnable to execute (never null)
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 are AsyncTaskExecutor.TIMEOUT_IMMEDIATE or AsyncTaskExecutor.TIMEOUT_INDEFINITE (the default as used by TaskExecutor.execute(Runnable)).

submit

public Future<?> submit(Runnable task)
Description copied from interface: AsyncTaskExecutor
Submit a Runnable task for execution, receiving a Future representing that task. The Future will return a null result upon completion.

Specified by:
submit in interface AsyncTaskExecutor
Parameters:
task - the Runnable to execute (never null)
Returns:
a Future representing pending completion of the task

submit

public <T> Future<T> submit(Callable<T> task)
Description copied from interface: AsyncTaskExecutor
Submit a Callable task for execution, receiving a Future representing that task. The Future will return the Callable's result upon completion.

Specified by:
submit in interface AsyncTaskExecutor
Parameters:
task - the Callable to execute (never null)
Returns:
a Future representing pending completion of the task

prefersShortLivedTasks

public boolean prefersShortLivedTasks()
This task executor prefers short-lived work units.

Specified by:
prefersShortLivedTasks in interface SchedulingTaskExecutor
Returns:
true if this TaskExecutor prefers short-lived tasks

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()

destroy

public void destroy()
Calls shutdown when the BeanFactory destroys the task executor instance.

Specified by:
destroy in interface DisposableBean
See Also:
shutdown()

shutdown

public void shutdown()
Perform a shutdown on the ThreadPoolExecutor.

See Also:
ThreadPoolExecutor.shutdown()