ScheduledThreadPoolExecutor

A {@link ThreadPoolExecutor} that can additionally schedule commands to run after a given delay, or to execute periodically. This class is preferable to {@link java.util.Timer} when multiple worker threads are needed, or when the additional flexibility or capabilities of {@link ThreadPoolExecutor} (which this class extends) are required.

<p>Delayed tasks execute no sooner than they are enabled, but without any real-time guarantees about when, after they are enabled, they will commence. Tasks scheduled for exactly the same execution time are enabled in first-in-first-out (FIFO) order of submission.

<p>When a submitted task is cancelled before it is run, execution is suppressed. By default, such a cancelled task is not automatically removed from the work queue until its delay elapses. While this enables further inspection and monitoring, it may also cause unbounded retention of cancelled tasks. To avoid this, use {@link #setRemoveOnCancelPolicy} to cause tasks to be immediately removed from the work queue at time of cancellation.

<p>Successive executions of a periodic task scheduled via {@link #scheduleAtFixedRate scheduleAtFixedRate} or {@link #scheduleWithFixedDelay scheduleWithFixedDelay} do not overlap. While different executions may be performed by different threads, the effects of prior executions <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> those of subsequent ones.

<p>While this class inherits from {@link ThreadPoolExecutor}, a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using {@code corePoolSize} threads and an unbounded queue, adjustments to {@code maximumPoolSize} have no useful effect. Additionally, it is almost never a good idea to set {@code corePoolSize} to zero or use {@code allowCoreThreadTimeOut} because this may leave the pool without threads to handle tasks once they become eligible to run.

<p>As with {@code ThreadPoolExecutor}, if not otherwise specified, this class uses {@link Executors#defaultThreadFactory} as the default thread factory, and {@link ThreadPoolExecutor.AbortPolicy} as the default rejected execution handler.

<p><b>Extension notes:</b> This class overrides the {@link ThreadPoolExecutor#execute(Runnable) execute} and {@link AbstractExecutorService#submit(Runnable) submit} methods to generate internal {@link ScheduledFuture} objects to control per-task delays and scheduling. To preserve functionality, any further overrides of these methods in subclasses must invoke superclass versions, which effectively disables additional task customization. However, this class provides alternative protected extension method {@code decorateTask} (one version each for {@code Runnable} and {@code Callable}) that can be used to customize the concrete task types used to execute commands entered via {@code execute}, {@code submit}, {@code schedule}, {@code scheduleAtFixedRate}, and {@code scheduleWithFixedDelay}. By default, a {@code ScheduledThreadPoolExecutor} uses a task type extending {@link FutureTask}. However, this may be modified or replaced using subclasses of the form:

<pre> {@code class CustomScheduledExecutor extends ScheduledThreadPoolExecutor {

static class CustomTask!(V) : RunnableScheduledFuture!(V) { ... }

protected !(V) RunnableScheduledFuture!(V) decorateTask( Runnable r, RunnableScheduledFuture!(V) task) { return new CustomTask!(V)(r, task); }

protected !(V) RunnableScheduledFuture!(V) decorateTask( Callable!(V) c, RunnableScheduledFuture!(V) task) { return new CustomTask!(V)(c, task); } // ... add constructors, etc. }}</pre>

@author Doug Lea

class ScheduledThreadPoolExecutor : ThreadPoolExecutor , ScheduledExecutorService {}

Constructors

this
this(int corePoolSize)

Creates a new {@code ScheduledThreadPoolExecutor} with the given core pool size.

this
this(int corePoolSize, ThreadFactory threadFactory)

Creates a new {@code ScheduledThreadPoolExecutor} with the given initial parameters.

this
this(int corePoolSize, RejectedExecutionHandler handler)

Creates a new {@code ScheduledThreadPoolExecutor} with the given initial parameters.

this
this(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler)

Creates a new {@code ScheduledThreadPoolExecutor} with the given initial parameters.

Members

Functions

canRunInCurrentRunState
bool canRunInCurrentRunState(RunnableScheduledFuture!V task)

Returns true if can run a task given current run state and run-after-shutdown parameters.

decorateTask
RunnableScheduledFuture!(V) decorateTask(Runnable runnable, RunnableScheduledFuture!(V) task)

Modifies or replaces the task used to execute a runnable. This method can be used to override the concrete class used for managing internal tasks. The default implementation simply returns the given task.

decorateTask
RunnableScheduledFuture!(V) decorateTask(Callable!(V) callable, RunnableScheduledFuture!(V) task)

Modifies or replaces the task used to execute a callable. This method can be used to override the concrete class used for managing internal tasks. The default implementation simply returns the given task.

execute
void execute(Runnable command)

Executes {@code command} with zero required delay. This has effect equivalent to {@link #schedule(Runnable,long,TimeUnit) schedule(command, 0, anyUnit)}. Note that inspections of the queue and of the list returned by {@code shutdownNow} will access the zero-delayed {@link ScheduledFuture}, not the {@code command} itself.

getContinueExistingPeriodicTasksAfterShutdownPolicy
bool getContinueExistingPeriodicTasksAfterShutdownPolicy()

Gets the policy on whether to continue executing existing periodic tasks even when this executor has been {@code shutdown}. In this case, executions will continue until {@code shutdownNow} or the policy is set to {@code false} when already shutdown. This value is by default {@code false}.

getExecuteExistingDelayedTasksAfterShutdownPolicy
bool getExecuteExistingDelayedTasksAfterShutdownPolicy()

Gets the policy on whether to execute existing delayed tasks even when this executor has been {@code shutdown}. In this case, these tasks will only terminate upon {@code shutdownNow}, or after setting the policy to {@code false} when already shutdown. This value is by default {@code true}.

getQueue
BlockingQueue!(Runnable) getQueue()

Returns the task queue used by this executor. Access to the task queue is intended primarily for debugging and monitoring. This queue may be in active use. Retrieving the task queue does not prevent queued tasks from executing.

getRemoveOnCancelPolicy
bool getRemoveOnCancelPolicy()

Gets the policy on whether cancelled tasks should be immediately removed from the work queue at time of cancellation. This value is by default {@code false}.

onShutdown
void onShutdown()

Cancels and clears the queue of all tasks that should not be run due to shutdown policy. Invoked within super.shutdown.

reExecutePeriodic
void reExecutePeriodic(RunnableScheduledFuture!V task)

Requeues a periodic task unless current run state precludes it. Same idea as delayedExecute except drops task rather than rejecting.

schedule
ScheduledFuture!(void) schedule(Runnable command, Duration delay)

@throws RejectedExecutionException {@inheritDoc} @throws NullPointerException {@inheritDoc}

schedule
ScheduledFuture!(V) schedule(Callable!(V) callable, Duration delay)

@throws RejectedExecutionException {@inheritDoc} @throws NullPointerException {@inheritDoc}

scheduleAtFixedRate
ScheduledFuture!void scheduleAtFixedRate(Runnable command, Duration initialDelay, Duration period)

Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is, executions will commence after {@code initialDelay}, then {@code initialDelay + period}, then {@code initialDelay + 2 * period}, and so on.

scheduleWithFixedDelay
ScheduledFuture!(void) scheduleWithFixedDelay(Runnable command, Duration initialDelay, Duration delay)

Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.

setContinueExistingPeriodicTasksAfterShutdownPolicy
void setContinueExistingPeriodicTasksAfterShutdownPolicy(bool value)

Sets the policy on whether to continue executing existing periodic tasks even when this executor has been {@code shutdown}. In this case, executions will continue until {@code shutdownNow} or the policy is set to {@code false} when already shutdown. This value is by default {@code false}.

setExecuteExistingDelayedTasksAfterShutdownPolicy
void setExecuteExistingDelayedTasksAfterShutdownPolicy(bool value)

Sets the policy on whether to execute existing delayed tasks even when this executor has been {@code shutdown}. In this case, these tasks will only terminate upon {@code shutdownNow}, or after setting the policy to {@code false} when already shutdown. This value is by default {@code true}.

setRemoveOnCancelPolicy
void setRemoveOnCancelPolicy(bool value)

Sets the policy on whether cancelled tasks should be immediately removed from the work queue at time of cancellation. This value is by default {@code false}.

shutdown
void shutdown()

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.

shutdownNow
List!(Runnable) shutdownNow()

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution. These tasks are drained (removed) from the task queue upon return from this method.

submit
Future!void submit(Runnable task)

@throws RejectedExecutionException {@inheritDoc} @throws NullPointerException {@inheritDoc}

submit
Future!(T) submit(Runnable task, T result)

@throws RejectedExecutionException {@inheritDoc} @throws NullPointerException {@inheritDoc}

submit
Future!(T) submit(Callable!(T) task)

@throws RejectedExecutionException {@inheritDoc} @throws NullPointerException {@inheritDoc}

triggerTime
long triggerTime(long delay)

Returns the nanoTime-based trigger time of a delayed action.

Variables

removeOnCancel
bool removeOnCancel;

True if ScheduledFutureTask.cancel should remove from queue.

Inherited Members

From ThreadPoolExecutor

tryTerminate
void tryTerminate()

Transitions to TERMINATED state if either (SHUTDOWN and pool and queue empty) or (STOP and pool empty). If otherwise eligible to terminate but workerCount is nonzero, interrupts an idle worker to ensure that shutdown signals propagate. This method must be called following any action that might make termination possible -- reducing worker count or removing tasks from the queue during shutdown. The method is non-private to allow access from ScheduledThreadPoolExecutor.

reject
void reject(Runnable command)

Invokes the rejected execution handler for the given command. Package-protected for use by ScheduledThreadPoolExecutor.

onShutdown
void onShutdown()

Performs any further cleanup following run state transition on invocation of shutdown. A no-op here, but used by ScheduledThreadPoolExecutor to cancel delayed tasks.

runWorker
void runWorker(Worker w)

Main worker run loop. Repeatedly gets tasks from queue and executes them, while coping with a number of issues:

execute
void execute(Runnable command)

Executes the given task sometime in the future. The task may execute in a new thread or in an existing pooled thread.

shutdown
void shutdown()

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.

shutdownNow
List!(Runnable) shutdownNow()

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution. These tasks are drained (removed) from the task queue upon return from this method.

isShutdown
bool isShutdown()
Undocumented in source. Be warned that the author may not have intended to support it.
isStopped
bool isStopped()

Used by ScheduledThreadPoolExecutor.

isTerminating
bool isTerminating()

Returns true if this executor is in the process of terminating after {@link #shutdown} or {@link #shutdownNow} but has not completely terminated. This method may be useful for debugging. A return of {@code true} reported a sufficient period after shutdown may indicate that submitted tasks have ignored or suppressed interruption, causing this executor not to properly terminate.

isTerminated
bool isTerminated()
Undocumented in source. Be warned that the author may not have intended to support it.
awaitTermination
bool awaitTermination(Duration timeout)
Undocumented in source. Be warned that the author may not have intended to support it.
finalize
void finalize()

@implNote Previous versions of this class had a finalize method that shut down this executor, but in this version, finalize does nothing.

setThreadFactory
void setThreadFactory(ThreadFactory threadFactory)

Sets the thread factory used to create new threads.

getThreadFactory
ThreadFactory getThreadFactory()

Returns the thread factory used to create new threads.

setRejectedExecutionHandler
void setRejectedExecutionHandler(RejectedExecutionHandler handler)

Sets a new handler for unexecutable tasks.

getRejectedExecutionHandler
RejectedExecutionHandler getRejectedExecutionHandler()

Returns the current handler for unexecutable tasks.

setCorePoolSize
void setCorePoolSize(int corePoolSize)

Sets the core number of threads. This overrides any value set in the constructor. If the new value is smaller than the current value, excess existing threads will be terminated when they next become idle. If larger, new threads will, if needed, be started to execute any queued tasks.

getCorePoolSize
int getCorePoolSize()

Returns the core number of threads.

prestartCoreThread
bool prestartCoreThread()

Starts a core thread, causing it to idly wait for work. This overrides the default policy of starting core threads only when new tasks are executed. This method will return {@code false} if all core threads have already been started.

ensurePrestart
void ensurePrestart()

Same as prestartCoreThread except arranges that at least one thread is started even if corePoolSize is 0.

prestartAllCoreThreads
int prestartAllCoreThreads()

Starts all core threads, causing them to idly wait for work. This overrides the default policy of starting core threads only when new tasks are executed.

allowsCoreThreadTimeOut
bool allowsCoreThreadTimeOut()

Returns true if this pool allows core threads to time out and terminate if no tasks arrive within the keepAlive time, being replaced if needed when new tasks arrive. When true, the same keep-alive policy applying to non-core threads applies also to core threads. When false (the default), core threads are never terminated due to lack of incoming tasks.

allowCoreThreadTimeOut
void allowCoreThreadTimeOut(bool value)

Sets the policy governing whether core threads may time out and terminate if no tasks arrive within the keep-alive time, being replaced if needed when new tasks arrive. When false, core threads are never terminated due to lack of incoming tasks. When true, the same keep-alive policy applying to non-core threads applies also to core threads. To avoid continual thread replacement, the keep-alive time must be greater than zero when setting {@code true}. This method should in general be called before the pool is actively used.

setMaximumPoolSize
void setMaximumPoolSize(int maximumPoolSize)

Sets the maximum allowed number of threads. This overrides any value set in the constructor. If the new value is smaller than the current value, excess existing threads will be terminated when they next become idle.

getMaximumPoolSize
int getMaximumPoolSize()

Returns the maximum allowed number of threads.

setKeepAliveTime
void setKeepAliveTime(Duration time)

Sets the thread keep-alive time, which is the amount of time that threads may remain idle before being terminated. Threads that wait this amount of time without processing a task will be terminated if there are more than the core number of threads currently in the pool, or if this pool {@linkplain #allowsCoreThreadTimeOut() allows core thread timeout}. This overrides any value set in the constructor.

getKeepAliveTime
long getKeepAliveTime()

Returns the thread keep-alive time, which is the amount of time that threads may remain idle before being terminated. Threads that wait this amount of time without processing a task will be terminated if there are more than the core number of threads currently in the pool, or if this pool {@linkplain #allowsCoreThreadTimeOut() allows core thread timeout}.

getQueue
BlockingQueue!(Runnable) getQueue()

Returns the task queue used by this executor. Access to the task queue is intended primarily for debugging and monitoring. This queue may be in active use. Retrieving the task queue does not prevent queued tasks from executing.

remove
bool remove(Runnable task)

Removes this task from the executor's internal queue if it is present, thus causing it not to be run if it has not already started.

purge
void purge()

Tries to remove from the work queue all {@link Future} tasks that have been cancelled. This method can be useful as a storage reclamation operation, that has no other impact on functionality. Cancelled tasks are never executed, but may accumulate in work queues until worker threads can actively remove them. Invoking this method instead tries to remove them now. However, this method may fail to remove tasks in the presence of interference by other threads.

getPoolSize
int getPoolSize()

Returns the current number of threads in the pool.

getActiveCount
int getActiveCount()

Returns the approximate number of threads that are actively executing tasks.

getLargestPoolSize
int getLargestPoolSize()

Returns the largest number of threads that have ever simultaneously been in the pool.

getTaskCount
long getTaskCount()

Returns the approximate total number of tasks that have ever been scheduled for execution. Because the states of tasks and threads may change dynamically during computation, the returned value is only an approximation.

getCompletedTaskCount
long getCompletedTaskCount()

Returns the approximate total number of tasks that have completed execution. Because the states of tasks and threads may change dynamically during computation, the returned value is only an approximation, but one that does not ever decrease across successive calls.

toString
string toString()

Returns a string identifying this pool, as well as its state, including indications of run state and estimated worker and task counts.

beforeExecute
void beforeExecute(Thread t, Runnable r)

Method invoked prior to executing the given Runnable in the given thread. This method is invoked by thread {@code t} that will execute task {@code r}, and may be used to re-initialize ThreadLocals, or to perform logging.

afterExecute
void afterExecute(Runnable r, Throwable t)

Method invoked upon completion of execution of the given Runnable. This method is invoked by the thread that executed the task. If non-null, the Throwable is the uncaught {@code RuntimeException} or {@code Error} that caused execution to terminate abruptly.

terminated
void terminated()

Method invoked when the Executor has terminated. Default implementation does nothing. Note: To properly nest multiple overridings, subclasses should generally invoke {@code super.terminated} within this method.

From ScheduledExecutorService

schedule
ScheduledFuture!void schedule(Runnable command, Duration delay)

Submits a one-shot task that becomes enabled after the given delay.

scheduleAtFixedRate
ScheduledFuture!void scheduleAtFixedRate(Runnable command, Duration initialDelay, Duration period)

Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is, executions will commence after {@code initialDelay}, then {@code initialDelay + period}, then {@code initialDelay + 2 * period}, and so on.

scheduleWithFixedDelay
ScheduledFuture!void scheduleWithFixedDelay(Runnable command, Duration initialDelay, Duration delay)

Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.

Meta