Top Description Fields Constructors Methods
org.springframework.scheduling.concurrent

public abstract Class ExecutorConfigurationSupport

extends CustomizableThreadFactory
implements BeanNameAware, ApplicationContextAware, InitializingBean, DisposableBean, SmartLifecycle, ApplicationListener<ContextClosedEvent>
Class Inheritance
All Implemented Interfaces
org.springframework.context.ApplicationListener, java.util.EventListener, org.springframework.context.SmartLifecycle, org.springframework.context.Phased, org.springframework.context.Lifecycle, org.springframework.beans.factory.DisposableBean, org.springframework.beans.factory.InitializingBean, org.springframework.context.ApplicationContextAware, org.springframework.beans.factory.Aware, org.springframework.beans.factory.BeanNameAware
Known Direct Subclasses
org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean, org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean, org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor, org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler
Annotations
@SuppressWarnings:serial
Imports
java.util.concurrent.ExecutorService, .Future, .RejectedExecutionHandler, .RunnableFuture, .ThreadFactory, .ThreadPoolExecutor, .TimeUnit, org.apache.commons.logging.Log, .LogFactory, org.springframework.beans.factory.BeanNameAware, .DisposableBean, .InitializingBean, org.springframework.context.ApplicationContext, .ApplicationContextAware, .ApplicationListener, .SmartLifecycle, org.springframework.context.event.ContextClosedEvent, org.springframework.lang.Nullable

Base class for setting up a java.util.concurrent.ExecutorService (typically a java.util.concurrent.ThreadPoolExecutor or java.util.concurrent.ScheduledThreadPoolExecutor).

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

Author
Juergen Hoeller
Since
3.0
See Also
java.util.concurrent.ExecutorService, java.util.concurrent.Executors, java.util.concurrent.ThreadPoolExecutor, java.util.concurrent.ScheduledThreadPoolExecutor

Field Summary

Modifier and TypeField and Description
private boolean
private ApplicationContext
private long
private String
private ExecutorService
private volatile boolean
private ExecutorLifecycleDelegate
protected final Log
private int
private RejectedExecutionHandler
private ThreadFactory
private boolean
private boolean

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
protected void
afterExecute(Runnable
the task that has been executed
task
,
Throwable
the exception thrown during execution, if any
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).

public void
afterPropertiesSet()

Implements org.springframework.beans.factory.InitializingBean.afterPropertiesSet.

Calls initialize() after the container applied all property values.
private void
awaitTerminationIfNecessary(ExecutorService executor)

Wait for the executor to terminate, according to the value of the "awaitTerminationSeconds" property.

protected void
beforeExecute(Thread
the thread to run the task
thread
,
Runnable
the task to be executed
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
the task to cancel (typically a RunnableFuture)
task
)

Cancel the given remaining task which never commenced execution, as returned from ExecutorService#shutdownNow().

public void
destroy()

Implements org.springframework.beans.factory.DisposableBean.destroy.

Calls shutdown when the BeanFactory destroys the executor instance.
public int
getPhase()

Overrides default org.springframework.context.SmartLifecycle.getPhase.

Return the lifecycle phase for pausing and resuming this executor.
public void
initialize()

Set up the ExecutorService.

protected abstract ExecutorService

Returns:

a new ExecutorService instance
initializeExecutor
(ThreadFactory
the ThreadFactory to use
threadFactory
,
RejectedExecutionHandler
the RejectedExecutionHandler to use
rejectedExecutionHandler
)

Create the target java.util.concurrent.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.

public void
initiateShutdown()

Initiate a shutdown on the underlying ExecutorService, rejecting further task submissions.

public boolean
isRunning()

Implements org.springframework.context.Lifecycle.isRunning.

Check whether this executor is not paused and has not been shut down either.
public void
onApplicationEvent(ContextClosedEvent
the event to respond to
event
)

Implements org.springframework.context.ApplicationListener.onApplicationEvent.

ContextClosedEvent handler for initiating an early shutdown.
public void
setAcceptTasksAfterContextClose(boolean acceptTasksAfterContextClose)

Set whether to accept further tasks after the application context close phase has begun.

public void
setApplicationContext(ApplicationContext
the ApplicationContext object to be used by this object
applicationContext
)

Implements org.springframework.context.ApplicationContextAware.setApplicationContext.

Set the ApplicationContext that this object runs in. Normally this call will be used to initialize the object.
public void
setAwaitTerminationMillis(long awaitTerminationMillis)

Variant of setAwaitTerminationSeconds with millisecond precision.

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.

public void
setBeanName(String
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.
name
)

Implements org.springframework.beans.factory.BeanNameAware.setBeanName.

Set the name of the bean in the bean factory that created this bean.
public void
setPhase(int phase)

Specify the lifecycle phase for pausing and resuming this executor.

public void
setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler)

Set the RejectedExecutionHandler to use for the ExecutorService.

public void
setThreadFactory(ThreadFactory threadFactory)

Set the ThreadFactory to use for the ExecutorService's thread pool.

public void
setThreadNamePrefix(String threadNamePrefix)

Overrides org.springframework.util.CustomizableThreadCreator.setThreadNamePrefix.

Specify the prefix to use for the names of newly created threads.
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.

public void
shutdown()

Perform a full shutdown on the underlying ExecutorService, according to the corresponding configuration settings.

public void
start()

Implements org.springframework.context.Lifecycle.start.

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

Implements org.springframework.context.Lifecycle.stop.

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

Overrides default org.springframework.context.SmartLifecycle.stop.

Pause this executor, triggering the given callback once all currently executing tasks have completed.
Inherited from org.springframework.scheduling.concurrent.CustomizableThreadFactory:
newThread

Field Detail

acceptTasksAfterContextCloseback to summary
private boolean acceptTasksAfterContextClose
applicationContextback to summary
private ApplicationContext applicationContext
Annotations
@Nullable
awaitTerminationMillisback to summary
private long awaitTerminationMillis
beanNameback to summary
private String beanName
Annotations
@Nullable
executorback to summary
private ExecutorService executor
Annotations
@Nullable
lateShutdownback to summary
private volatile boolean lateShutdown
lifecycleDelegateback to summary
private ExecutorLifecycleDelegate lifecycleDelegate
Annotations
@Nullable
loggerback to summary
protected final Log logger
phaseback to summary
private int phase
rejectedExecutionHandlerback to summary
private RejectedExecutionHandler rejectedExecutionHandler
threadFactoryback to summary
private ThreadFactory threadFactory
threadNamePrefixSetback to summary
private boolean threadNamePrefixSet
waitForTasksToCompleteOnShutdownback to summary
private boolean waitForTasksToCompleteOnShutdown

Constructor Detail

ExecutorConfigurationSupportback to summary
public ExecutorConfigurationSupport()

Method Detail

afterExecuteback to summary
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).

Parameters
task:Runnable

the task that has been executed

ex:Throwable

the exception thrown during execution, if any

Since
6.1
See Also
ThreadPoolExecutor#afterExecute(Runnable, Throwable)
afterPropertiesSetback to summary
public void afterPropertiesSet()

Implements org.springframework.beans.factory.InitializingBean.afterPropertiesSet.

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

Annotations
@Override
See Also
initialize()
awaitTerminationIfNecessaryback to summary
private void awaitTerminationIfNecessary(ExecutorService executor)

Wait for the executor to terminate, according to the value of the "awaitTerminationSeconds" property.

beforeExecuteback to summary
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:Thread

the thread to run the task

task:Runnable

the task to be executed

Since
6.1
See Also
ThreadPoolExecutor#beforeExecute(Thread, Runnable)
cancelRemainingTaskback to summary
protected void cancelRemainingTask(Runnable task)

Cancel the given remaining task which never commenced execution, as returned from ExecutorService#shutdownNow().

Parameters
task:Runnable

the task to cancel (typically a RunnableFuture)

Since
5.0.5
See Also
shutdown(), RunnableFuture#cancel(boolean)
destroyback to summary
public void destroy()

Implements org.springframework.beans.factory.DisposableBean.destroy.

Calls shutdown when the BeanFactory destroys the executor instance.

Annotations
@Override
See Also
shutdown()
getPhaseback to summary
public int getPhase()

Overrides default org.springframework.context.SmartLifecycle.getPhase.

Return the lifecycle phase for pausing and resuming this executor.

Annotations
@Override
Since
6.1
See Also
setPhase
initializeback to summary
public void initialize()

Set up the ExecutorService.

initializeExecutorback to summary
protected abstract ExecutorService initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler)

Create the target java.util.concurrent.ExecutorService instance. Called by afterPropertiesSet.

Parameters
threadFactory:ThreadFactory

the ThreadFactory to use

rejectedExecutionHandler:RejectedExecutionHandler

the RejectedExecutionHandler to use

Returns:ExecutorService

a new ExecutorService instance

See Also
afterPropertiesSet()
initiateEarlyShutdownback to summary
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()
initiateShutdownback to summary
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(), java.util.concurrent.ExecutorService#shutdown()
isRunningback to summary
public boolean isRunning()

Implements org.springframework.context.Lifecycle.isRunning.

Check whether this executor is not paused and has not been shut down either.

Returns:boolean

Doc from org.springframework.context.Lifecycle.isRunning.

whether the component is currently running

Annotations
@Override
Since
6.1
See Also
start(), stop()
onApplicationEventback to summary
public void onApplicationEvent(ContextClosedEvent event)

Implements org.springframework.context.ApplicationListener.onApplicationEvent.

ContextClosedEvent handler for initiating an early shutdown.

Parameters
event:ContextClosedEvent

Doc from org.springframework.context.ApplicationListener.onApplicationEvent.

the event to respond to

Annotations
@Override
Since
6.1
See Also
initiateShutdown()
setAcceptTasksAfterContextCloseback to summary
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
org.springframework.context.ConfigurableApplicationContext#close(), DisposableBean#destroy(), shutdown(), setAwaitTerminationSeconds
setApplicationContextback to summary
public void setApplicationContext(ApplicationContext applicationContext)

Implements org.springframework.context.ApplicationContextAware.setApplicationContext.

Doc from org.springframework.context.ApplicationContextAware.setApplicationContext.

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 org.springframework.beans.factory.InitializingBean#afterPropertiesSet() or a custom init-method. Invoked after ResourceLoaderAware#setResourceLoader, ApplicationEventPublisherAware#setApplicationEventPublisher and MessageSourceAware, if applicable.

Parameters
applicationContext:ApplicationContext

the ApplicationContext object to be used by this object

Annotations
@Override
setAwaitTerminationMillisback to summary
public void setAwaitTerminationMillis(long awaitTerminationMillis)

Variant of setAwaitTerminationSeconds with millisecond precision.

Since
5.2.4
See Also
setAwaitTerminationSeconds
setAwaitTerminationSecondsback to summary
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, java.util.concurrent.ExecutorService#shutdown(), java.util.concurrent.ExecutorService#awaitTermination
setBeanNameback to summary
public void setBeanName(String name)

Implements org.springframework.beans.factory.BeanNameAware.setBeanName.

Doc from org.springframework.beans.factory.BeanNameAware.setBeanName.

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.

Parameters
name:String

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.

Annotations
@Override
setPhaseback to summary
public void setPhase(int phase)

Specify the lifecycle phase for pausing and resuming this executor. The default is DEFAULT_PHASE.

Since
6.1
See Also
SmartLifecycle#getPhase()
setRejectedExecutionHandlerback to summary
public void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler)

Set the RejectedExecutionHandler to use for the ExecutorService. The default is the ExecutorService's default abort policy.

See Also
java.util.concurrent.ThreadPoolExecutor.AbortPolicy
setThreadFactoryback to summary
public void setThreadFactory(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 org.springframework.jndi.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
java.util.concurrent.Executors#defaultThreadFactory(), jakarta.enterprise.concurrent.ManagedThreadFactory, DefaultManagedAwareThreadFactory
setThreadNamePrefixback to summary
public void setThreadNamePrefix(String threadNamePrefix)

Overrides org.springframework.util.CustomizableThreadCreator.setThreadNamePrefix.

Doc from org.springframework.util.CustomizableThreadCreator.setThreadNamePrefix.

Specify the prefix to use for the names of newly created threads. Default is "SimpleAsyncTaskExecutor-".

Annotations
@Override
setWaitForTasksToCompleteOnShutdownback to summary
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 - e.g. 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
java.util.concurrent.ExecutorService#shutdown(), java.util.concurrent.ExecutorService#shutdownNow(), shutdown(), setAwaitTerminationSeconds
shutdownback to summary
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, setAwaitTerminationMillis, java.util.concurrent.ExecutorService#shutdown(), java.util.concurrent.ExecutorService#shutdownNow(), java.util.concurrent.ExecutorService#awaitTermination
startback to summary
public void start()

Implements org.springframework.context.Lifecycle.start.

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

Annotations
@Override
Since
6.1
stopback to summary
public void stop()

Implements org.springframework.context.Lifecycle.stop.

Pause this executor, not waiting for tasks to complete.

Annotations
@Override
Since
6.1
stopback to summary
public void stop(Runnable callback)

Overrides default org.springframework.context.SmartLifecycle.stop.

Pause this executor, triggering the given callback once all currently executing tasks have completed.

Annotations
@Override
Since
6.1