Package org.springframework.scheduling.concurrent

# Class ExecutorConfigurationSupport

java.lang.Object
org.springframework.util.CustomizableThreadCreator
org.springframework.scheduling.concurrent.CustomizableThreadFactory
org.springframework.scheduling.concurrent.ExecutorConfigurationSupport

All Implemented Interfaces:
  `Serializable`, `ThreadFactory`, `EventListener`, `org.springframework.beans.factory.Aware`, `org.springframework.beans.factory.BeanNameAware`, `org.springframework.beans.factory.DisposableBean`, `org.springframework.beans.factory.InitializingBean`, `ApplicationContextAware`, `ApplicationListener<ContextClosedEvent>`, `Lifecycle`, `Phased`, `SmartLifecycle`

Direct Known Subclasses:
  `ScheduledExecutorFactoryBean`, `ThreadPoolExecutorFactoryBean`, `ThreadPoolTaskExecutor`, `ThreadPoolTaskScheduler`

public abstract class ExecutorConfigurationSupport extends CustomizableThreadFactory implements org.springframework.beans.factory.BeanNameAware, ApplicationContextAware, org.springframework.beans.factory.InitializingBean, org.springframework.beans.factory.DisposableBean, SmartLifecycle, ApplicationListener<ContextClosedEvent>
Base class for setting up a `ExecutorService` (typically a `ThreadPoolExecutor` or `ScheduledThreadPoolExecutor`).

Defines common configuration settings and common lifecycle handling, inheriting thread customization options (name, priority, etc) from `CustomizableThreadCreator`.

Since:
  3.0
Author:
  Juergen Hoeller
See Also:
  - `ExecutorService`
  - `Executors`
  - `ThreadPoolExecutor`
  - `ScheduledThreadPoolExecutor`
  - Serialized Form

## Field Summary

Fields
Modifier and Type
Field
Description
`static final int`
`DEFAULT_PHASE`
The default phase for an executor `SmartLifecycle`: `Integer.MAX_VALUE / 2`.
`protected final org.apache.commons.logging.Log`
`logger`

## Constructor Summary

Constructors
Constructor
Description
`ExecutorConfigurationSupport()`

## Method Summary

Modifier and Type
Method
Description
`protected void`
`afterExecute(Runnable task, Throwable ex)`
An after-execute callback for framework subclasses to delegate to (for start/stop handling), and possibly also for custom subclasses to extend (making sure to call this implementation as well).
`void`
`afterPropertiesSet()`
Calls `initialize()` after the container applied all property values.
`protected void`
`beforeExecute(Thread thread, Runnable task)`
A before-execute callback for framework subclasses to delegate to (for start/stop handling), and possibly also for custom subclasses to extend (making sure to call this implementation as well).
`protected void`
`cancelRemainingTask(Runnable task)`
Cancel the given remaining task which never commenced execution, as returned from `ExecutorService.shutdownNow()`.
`void`
`destroy()`
Calls `shutdown` when the BeanFactory destroys the executor instance.
`int`
`getPhase()`
Return the lifecycle phase for pausing and resuming this executor.
`void`
`initialize()`
Set up the ExecutorService.
`protected abstract ExecutorService`
`initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler)`
Create the target `ExecutorService` instance.
`protected void`
`initiateEarlyShutdown()`
Early shutdown signal: do not trigger further tasks, let existing tasks complete before hitting the actual destruction step in the `shutdown()` method.
`void`
`initiateShutdown()`
Initiate a shutdown on the underlying ExecutorService, rejecting further task submissions.
`boolean`
`isRunning()`
Check whether this executor is not paused and has not been shut down either.
`void`
`onApplicationEvent(ContextClosedEvent event)`
`ContextClosedEvent` handler for initiating an early shutdown.
`void`
`setAcceptTasksAfterContextClose(boolean acceptTasksAfterContextClose)`
Set whether to accept further tasks after the application context close phase has begun.
`void`
`setApplicationContext(ApplicationContext applicationContext)`
Set the ApplicationContext that this object runs in.
`void`
`setAwaitTerminationMillis(long awaitTerminationMillis)`
Variant of `setAwaitTerminationSeconds(int)` with millisecond precision.
`void`
`setAwaitTerminationSeconds(int awaitTerminationSeconds)`
Set the maximum number of seconds that this executor is supposed to block on shutdown in order to wait for remaining tasks to complete their execution before the rest of the container continues to shut down.
`void`
`setBeanName(String name)`
`void`
`setPhase(int phase)`
Specify the lifecycle phase for pausing and resuming this executor.
`void`
`setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler)`
Set the RejectedExecutionHandler to use for the ExecutorService.
`void`
`setThreadFactory(ThreadFactory threadFactory)`
Set the ThreadFactory to use for the ExecutorService's thread pool.
`void`
`setThreadNamePrefix(String threadNamePrefix)`
`void`
`setVirtualThreads(boolean virtualThreads)`
Specify whether to use virtual threads instead of platform threads.
`void`
`setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown)`
Set whether to wait for scheduled tasks to complete on shutdown, not interrupting running tasks and executing all tasks in the queue.
`void`
`shutdown()`
Perform a full shutdown on the underlying ExecutorService, according to the corresponding configuration settings.
`void`
`start()`
Resume this executor if paused before (otherwise a no-op).
`void`
`stop()`
Pause this executor, not waiting for tasks to complete.
`void`
`stop(Runnable callback)`
Pause this executor, triggering the given callback once all currently executing tasks have completed.

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

### Methods inherited from interface org.springframework.context.ApplicationListener

`supportsAsyncExecution`

### Methods inherited from interface org.springframework.context.SmartLifecycle

`isAutoStartup`

## Field Details

### DEFAULT_PHASE

public static final int DEFAULT_PHASE
The default phase for an executor `SmartLifecycle`: `Integer.MAX_VALUE / 2`.

This is different from the default phase `Integer.MAX_VALUE` associated with other `SmartLifecycle` implementations, putting the typically auto-started executor/scheduler beans into an earlier startup phase and a later shutdown phase while still leaving room for regular `Lifecycle` components with the common phase 0.

Since:
  6.2
See Also:
  - `getPhase()`
  - `SmartLifecycle.DEFAULT_PHASE`
  - `DefaultLifecycleProcessor.setTimeoutPerShutdownPhase(long)`
  - Constant Field Values

### logger

protected final org.apache.commons.logging.Log logger

## Constructor Details

### ExecutorConfigurationSupport

public ExecutorConfigurationSupport()

## Method Details

### setVirtualThreads

public void setVirtualThreads(boolean virtualThreads)
Specify whether to use virtual threads instead of platform threads. This is off by default, setting up a traditional platform thread pool.

Set this flag to `true` on Java 21 or higher for a tightly managed thread pool setup with virtual threads. In contrast to `SimpleAsyncTaskExecutor`, this is integrated with Spring's lifecycle management for stopping and restarting execution threads, including an early stop signal for a graceful shutdown arrangement.

Specify either this or `setThreadFactory(java.util.concurrent.ThreadFactory)`, not both.

Since:
  6.2
See Also:
  - `setThreadFactory(java.util.concurrent.ThreadFactory)`
  - `VirtualThreadTaskExecutor.getVirtualThreadFactory()`
  - `SimpleAsyncTaskExecutor.setVirtualThreads(boolean)`

### setThreadFactory

public void setThreadFactory(@Nullable ThreadFactory threadFactory)
Set the ThreadFactory to use for the ExecutorService's thread pool. The default is the underlying ExecutorService's default thread factory.

In a Jakarta EE or other managed environment with JSR-236 support, consider specifying a JNDI-located ManagedThreadFactory: by default, to be found at "java:comp/DefaultManagedThreadFactory". Use the "jee:jndi-lookup" namespace element in XML or the programmatic `JndiLocatorDelegate` for convenient lookup. Alternatively, consider using Spring's `DefaultManagedAwareThreadFactory` with its fallback to local threads in case of no managed thread factory found.

See Also:
  - `Executors.defaultThreadFactory()`
  - `ManagedThreadFactory`
  - `DefaultManagedAwareThreadFactory`

### setThreadNamePrefix

public void setThreadNamePrefix(@Nullable String threadNamePrefix)

Overrides:
  `setThreadNamePrefix` in class `org.springframework.util.CustomizableThreadCreator`

### setRejectedExecutionHandler

public void setRejectedExecutionHandler(@Nullable RejectedExecutionHandler rejectedExecutionHandler)
Set the RejectedExecutionHandler to use for the ExecutorService. The default is the ExecutorService's default abort policy.

See Also:
  - `ThreadPoolExecutor.AbortPolicy`

### setAcceptTasksAfterContextClose

public void setAcceptTasksAfterContextClose(boolean acceptTasksAfterContextClose)
Set whether to accept further tasks after the application context close phase has begun.

The default is `false` as of 6.1, triggering an early soft shutdown of the executor and therefore rejecting any further task submissions. Switch this to `true` in order to let other components submit tasks even during their own stop and destruction callbacks, at the expense of a longer shutdown phase. The executor will not go through a coordinated lifecycle stop phase then but rather only stop tasks on its own shutdown.

`acceptTasksAfterContextClose=true` like behavior also follows from `"waitForTasksToCompleteOnShutdown"` which effectively is a specific variant of this flag, replacing the early soft shutdown in the concurrent managed stop phase with a serial soft shutdown in the executor's destruction step, with individual awaiting according to the `"awaitTerminationSeconds"` property.

This flag will only have effect when the executor is running in a Spring application context and able to receive the `ContextClosedEvent`. Also, note that `ThreadPoolTaskExecutor` effectively accepts tasks after context close by default, in combination with a coordinated lifecycle stop, unless `"strictEarlyShutdown"` has been specified.

Since:
  6.1
See Also:
  - `ConfigurableApplicationContext.close()`
  - `DisposableBean.destroy()`
  - `shutdown()`
  - `setAwaitTerminationSeconds(int)`

### setWaitForTasksToCompleteOnShutdown

public void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown)
Set whether to wait for scheduled tasks to complete on shutdown, not interrupting running tasks and executing all tasks in the queue.

The default is `false`, with a coordinated lifecycle stop first (unless `"acceptTasksAfterContextClose"` has been set) and then an immediate shutdown through interrupting ongoing tasks and clearing the queue. Switch this flag to `true` if you prefer fully completed tasks at the expense of a longer shutdown phase. The executor will not go through a coordinated lifecycle stop phase then but rather only stop and wait for task completion on its own shutdown.

Note that Spring's container shutdown continues while ongoing tasks are being completed. If you want this executor to block and wait for the termination of tasks before the rest of the container continues to shut down - for example, in order to keep up other resources that your tasks may need -, set the `"awaitTerminationSeconds"` property instead of or in addition to this property.

See Also:
  - `ExecutorService.shutdown()`
  - `ExecutorService.shutdownNow()`
  - `shutdown()`
  - `setAwaitTerminationSeconds(int)`

### setAwaitTerminationSeconds

public void setAwaitTerminationSeconds(int awaitTerminationSeconds)
Set the maximum number of seconds that this executor is supposed to block on shutdown in order to wait for remaining tasks to complete their execution before the rest of the container continues to shut down. This is particularly useful if your remaining tasks are likely to need access to other resources that are also managed by the container.

By default, this executor won't wait for the termination of tasks at all. It will either shut down immediately, interrupting ongoing tasks and clearing the remaining task queue - or, if the `"waitForTasksToCompleteOnShutdown"` flag has been set to `true`, it will continue to fully execute all ongoing tasks as well as all remaining tasks in the queue, in parallel to the rest of the container shutting down.

In either case, if you specify an await-termination period using this property, this executor will wait for the given time (max) for the termination of tasks. As a rule of thumb, specify a significantly higher timeout here if you set "waitForTasksToCompleteOnShutdown" to `true` at the same time, since all remaining tasks in the queue will still get executed - in contrast to the default shutdown behavior where it's just about waiting for currently executing tasks that aren't reacting to thread interruption.

See Also:
  - `setAwaitTerminationMillis(long)`
  - `ExecutorService.shutdown()`
  - `ExecutorService.awaitTermination(long, java.util.concurrent.TimeUnit)`

### setAwaitTerminationMillis

public void setAwaitTerminationMillis(long awaitTerminationMillis)
Variant of `setAwaitTerminationSeconds(int)` with millisecond precision.

Since:
  5.2.4
See Also:
  - `setAwaitTerminationSeconds(int)`

### setPhase

public void setPhase(int phase)
Specify the lifecycle phase for pausing and resuming this executor.

The default for executors/schedulers is `DEFAULT_PHASE` as of 6.2, for stopping after other `SmartLifecycle` implementations.

Since:
  6.1
See Also:
  - `SmartLifecycle.getPhase()`

### getPhase

public int getPhase()
Return the lifecycle phase for pausing and resuming this executor.

Specified by:
  `getPhase` in interface `Phased`
Specified by:
  `getPhase` in interface `SmartLifecycle`
Since:
  6.1
See Also:
  - `setPhase(int)`

### setBeanName

public void setBeanName(String name)

Specified by:
  `setBeanName` in interface `org.springframework.beans.factory.BeanNameAware`

### setApplicationContext

public void setApplicationContext(ApplicationContext applicationContext)
Description copied from interface: `ApplicationContextAware`
Set the ApplicationContext that this object runs in. Normally this call will be used to initialize the object.

Invoked after population of normal bean properties but before an init callback such as `InitializingBean.afterPropertiesSet()` or a custom init-method. Invoked after `ResourceLoaderAware.setResourceLoader(org.springframework.core.io.ResourceLoader)`, `ApplicationEventPublisherAware.setApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher)` and `MessageSourceAware`, if applicable.

Specified by:
  `setApplicationContext` in interface `ApplicationContextAware`
Parameters:
  `applicationContext` - the ApplicationContext object to be used by this object
See Also:
  - `BeanInitializationException`

### afterPropertiesSet

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

Specified by:
  `afterPropertiesSet` in interface `org.springframework.beans.factory.InitializingBean`
See Also:
  - `initialize()`

### initialize

public void initialize()
Set up the ExecutorService.

### initializeExecutor

protected abstract ExecutorService initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler)
Create the target `ExecutorService` instance. Called by `afterPropertiesSet`.

Parameters:
  `threadFactory` - the ThreadFactory to use
  `rejectedExecutionHandler` - the RejectedExecutionHandler to use
Returns:
  a new ExecutorService instance
See Also:
  - `afterPropertiesSet()`

### destroy

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

Specified by:
  `destroy` in interface `org.springframework.beans.factory.DisposableBean`
See Also:
  - `shutdown()`

### initiateShutdown

public void initiateShutdown()
Initiate a shutdown on the underlying ExecutorService, rejecting further task submissions.

The executor will not accept further tasks and will prevent further scheduling of periodic tasks, letting existing tasks complete still. This step is non-blocking and can be applied as an early shutdown signal before following up with a full `shutdown()` call later on.

Automatically called for early shutdown signals on `context close`. Can be manually called as well, in particular outside a container.

Since:
  6.1
See Also:
  - `shutdown()`
  - `ExecutorService.shutdown()`

### shutdown

public void shutdown()
Perform a full shutdown on the underlying ExecutorService, according to the corresponding configuration settings.

This step potentially blocks for the configured termination period, waiting for remaining tasks to complete. For an early shutdown signal to not accept further tasks, call `initiateShutdown()` first.

See Also:
  - `setWaitForTasksToCompleteOnShutdown(boolean)`
  - `setAwaitTerminationMillis(long)`
  - `ExecutorService.shutdown()`
  - `ExecutorService.shutdownNow()`
  - `ExecutorService.awaitTermination(long, java.util.concurrent.TimeUnit)`

### cancelRemainingTask

protected void cancelRemainingTask(Runnable task)
Cancel the given remaining task which never commenced execution, as returned from `ExecutorService.shutdownNow()`.

Parameters:
  `task` - the task to cancel (typically a `RunnableFuture`)
Since:
  5.0.5
See Also:
  - `shutdown()`
  - `Future.cancel(boolean)`

### start

public void start()
Resume this executor if paused before (otherwise a no-op).

Specified by:
  `start` in interface `Lifecycle`
Since:
  6.1
See Also:
  - `SmartLifecycle.isAutoStartup()`

### stop

public void stop()
Pause this executor, not waiting for tasks to complete.

Specified by:
  `stop` in interface `Lifecycle`
Since:
  6.1
See Also:
  - `SmartLifecycle.stop(Runnable)`
  - `DisposableBean.destroy()`

### stop

public void stop(Runnable callback)
Pause this executor, triggering the given callback once all currently executing tasks have completed.

Specified by:
  `stop` in interface `SmartLifecycle`
Since:
  6.1
See Also:
  - `Lifecycle.stop()`
  - `SmartLifecycle.getPhase()`

### isRunning

public boolean isRunning()
Check whether this executor is not paused and has not been shut down either.

Specified by:
  `isRunning` in interface `Lifecycle`
Returns:
  whether the component is currently running
Since:
  6.1
See Also:
  - `start()`
  - `stop()`

### beforeExecute

protected void beforeExecute(Thread thread, Runnable task)
A before-execute callback for framework subclasses to delegate to (for start/stop handling), and possibly also for custom subclasses to extend (making sure to call this implementation as well).

Parameters:
  `thread` - the thread to run the task
  `task` - the task to be executed
Since:
  6.1
See Also:
  - `ThreadPoolExecutor.beforeExecute(Thread, Runnable)`

### afterExecute

protected void afterExecute(Runnable task, @Nullable Throwable ex)
An after-execute callback for framework subclasses to delegate to (for start/stop handling), and possibly also for custom subclasses to extend (making sure to call this implementation as well).

Parameters:
  `task` - the task that has been executed
  `ex` - the exception thrown during execution, if any
Since:
  6.1
See Also:
  - `ThreadPoolExecutor.afterExecute(Runnable, Throwable)`

### onApplicationEvent

public void onApplicationEvent(ContextClosedEvent event)
`ContextClosedEvent` handler for initiating an early shutdown.

Specified by:
  `onApplicationEvent` in interface `ApplicationListener<ContextClosedEvent>`
Parameters:
  `event` - the event to respond to
Since:
  6.1
See Also:
  - `initiateShutdown()`

### initiateEarlyShutdown

protected void 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()`.

Since:
  6.1.4
See Also:
  - `initiateShutdown()`