org.springframework.scheduling.concurrent

## 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, AsyncTaskExecutor, TaskExecutor, SchedulingTaskExecutor

      public class ThreadPoolTaskExecutor
      extends ExecutorConfigurationSupport
      implements SchedulingTaskExecutor

  JavaBean that allows for configuring a JDK 1.5 `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 (e.g. through JMX), providing several useful attributes: "corePoolSize", "maxPoolSize", "keepAliveSeconds" (all supporting updates at runtime); "poolSize", "activeCount" (for introspection only).

  For an alternative, you may set up a ThreadPoolExecutor instance directly using constructor injection, or use a factory method definition that points to the JDK 1.5 `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 as well as the JDK 1.5 `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`.

  If you prefer native `ExecutorService` exposure instead, consider `ThreadPoolExecutorFactoryBean` as an alternative to this class.

  Since:
    2.0
  Author:
    Juergen Hoeller
  See Also:
    `TaskExecutor`, `ThreadPoolExecutor`, `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 and Description
    `ThreadPoolTaskExecutor()`

  - ### Method Summary

    Methods
    Modifier and Type | Method and Description
    --- | ---
    `protected BlockingQueue<Runnable>` | `createQueue(int queueCapacity)` Create the BlockingQueue to use for the ThreadPoolExecutor.
    `void` | `execute(Runnable task)` Execute the given `task`.
    `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.
    `ThreadPoolExecutor` | `getThreadPoolExecutor()` Return the underlying ThreadPoolExecutor for native access.
    `protected ExecutorService` | `initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler)` Create the target `ExecutorService` instance.
    `boolean` | `prefersShortLivedTasks()` This task executor prefers short-lived work units.
    `void` | `setAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut)` Specify whether to allow core threads to time out.
    `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.
    `<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.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`

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- - ### 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 Java 6 or above. On Java 5, consider switching to the backport-concurrent version of ThreadPoolTaskExecutor which also supports this feature.

      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`

    - #### initializeExecutor

          protected ExecutorService initializeExecutor(ThreadFactory threadFactory,
                                           RejectedExecutionHandler rejectedExecutionHandler)

      Description copied from class: `ExecutorConfigurationSupport`
      Create the target `ExecutorService` instance. Called by `afterPropertiesSet`.
      Specified by:
        `initializeExecutor` in class `ExecutorConfigurationSupport`
      Parameters:
        `threadFactory` - the ThreadFactory to use
        `rejectedExecutionHandler` - 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: `TaskExecutor`
      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.

      Specified by:
        `execute` in interface `Executor`
      Specified by:
        `execute` in interface `TaskExecutor`
      Parameters:
        `task` - the `Runnable` to execute (never `null`)

    - #### 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