Top Description Inners Fields Constructors Methods
java.util.concurrent

public Class ScheduledThreadPoolExecutor

extends ThreadPoolExecutor
implements ScheduledExecutorService
Class Inheritance
All Implemented Interfaces
java.util.concurrent.ScheduledExecutorService, java.util.concurrent.ExecutorService, java.lang.AutoCloseable, java.util.concurrent.Executor
Static Imports
java.util.concurrent.TimeUnit.MILLISECONDS, .TimeUnit.NANOSECONDS

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

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.

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 setRemoveOnCancelPolicy to cause tasks to be immediately removed from the work queue at time of cancellation.

Successive executions of a periodic task scheduled via scheduleAtFixedRate or scheduleWithFixedDelay do not overlap. While different executions may be performed by different threads, the effects of prior executions happen-before those of subsequent ones.

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

As with ThreadPoolExecutor, if not otherwise specified, this class uses Executors#defaultThreadFactory as the default thread factory, and ThreadPoolExecutor.AbortPolicy as the default rejected execution handler.

Extension Notes

This class overrides the execute and submit methods to generate internal 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 decorateTask (one version each for Runnable and Callable) that can be used to customize the concrete task types used to execute commands entered via execute, submit, schedule, scheduleAtFixedRate, and scheduleWithFixedDelay. By default, a ScheduledThreadPoolExecutor uses a task type extending FutureTask. However, this may be modified or replaced using subclasses of the form:

 public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor {

  static class CustomTask<V> implements 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.
}
Author
Doug Lea
Since
1.5

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static class
private class

Field Summary

Modifier and TypeField and Description
private volatile boolean
continueExistingPeriodicTasksAfterShutdown

False if should cancel/suppress periodic tasks on shutdown.

private static final long
DEFAULT_KEEPALIVE_MILLIS

The default keep-alive time for pool threads.

private volatile boolean
executeExistingDelayedTasksAfterShutdown

False if should cancel non-periodic not-yet-expired tasks on shutdown.

pack-priv volatile boolean
removeOnCancel

True if ScheduledFutureTask.cancel should remove from queue.

private static final AtomicLong
sequencer

Sequence number to break scheduling ties, and in turn to guarantee FIFO order among tied entries.

Constructor Summary

AccessConstructor and Description
public
ScheduledThreadPoolExecutor(int
the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
corePoolSize
)

Creates a new ScheduledThreadPoolExecutor with the given core pool size.

public
ScheduledThreadPoolExecutor(int
the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
corePoolSize
,
ThreadFactory
the factory to use when the executor creates a new thread
threadFactory
)

Creates a new ScheduledThreadPoolExecutor with the given initial parameters.

public
ScheduledThreadPoolExecutor(int
the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
corePoolSize
,
RejectedExecutionHandler
the handler to use when execution is blocked because the thread bounds and queue capacities are reached
handler
)

Creates a new ScheduledThreadPoolExecutor with the given initial parameters.

public
ScheduledThreadPoolExecutor(int
the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
corePoolSize
,
ThreadFactory
the factory to use when the executor creates a new thread
threadFactory
,
RejectedExecutionHandler
the handler to use when execution is blocked because the thread bounds and queue capacities are reached
handler
)

Creates a new ScheduledThreadPoolExecutor with the given initial parameters.

Method Summary

Modifier and TypeMethod and Description
pack-priv boolean
canRunInCurrentRunState(RunnableScheduledFuture<?> task)

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

protected <
the type of the task's result
V
>
RunnableScheduledFuture<V>

Returns:

a task that can execute the runnable
decorateTask
(Runnable
the submitted Runnable
runnable
,
RunnableScheduledFuture<V>
the task created to execute the runnable
task
)

Modifies or replaces the task used to execute a runnable.

protected <
the type of the task's result
V
>
RunnableScheduledFuture<V>

Returns:

a task that can execute the callable
decorateTask
(Callable<V>
the submitted Callable
callable
,
RunnableScheduledFuture<V>
the task created to execute the callable
task
)

Modifies or replaces the task used to execute a callable.

private void
delayedExecute(RunnableScheduledFuture<?>
the task
task
)

Main execution method for delayed or periodic tasks.

public void
execute(Runnable
the runnable task
command
)

Overrides java.util.concurrent.ThreadPoolExecutor.execute.

Implements java.util.concurrent.Executor.execute.

Executes command with zero required delay.

public boolean

Returns:

true if will continue after shutdown
getContinueExistingPeriodicTasksAfterShutdownPolicy
()

Gets the policy on whether to continue executing existing periodic tasks even when this executor has been shutdown.

public boolean

Returns:

true if will execute after shutdown
getExecuteExistingDelayedTasksAfterShutdownPolicy
()

Gets the policy on whether to execute existing delayed tasks even when this executor has been shutdown.

public BlockingQueue<Runnable>

Returns:

the task queue
getQueue
()

Overrides java.util.concurrent.ThreadPoolExecutor.getQueue.

Returns the task queue used by this executor.

public boolean

Returns:

true if cancelled tasks are immediately removed from the queue
getRemoveOnCancelPolicy
()

Gets the policy on whether cancelled tasks should be immediately removed from the work queue at time of cancellation.

pack-priv void
onShutdown()

Overrides java.util.concurrent.ThreadPoolExecutor.onShutdown.

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

private long
overflowFree(long delay)

Constrains the values of all delays in the queue to be within Long.MAX_VALUE of each other, to avoid overflow in compareTo.

pack-priv void
reExecutePeriodic(RunnableScheduledFuture<?>
the task
task
)

Requeues a periodic task unless current run state precludes it.

public ScheduledFuture<?>
schedule(Runnable
the task to execute
command
,
long
the time from now to delay execution
delay
,
TimeUnit
the time unit of the delay parameter
unit
)

Implements java.util.concurrent.ScheduledExecutorService.schedule.

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

public <V> ScheduledFuture<V>
schedule(Callable<V>
the function to execute
callable
,
long
the time from now to delay execution
delay
,
TimeUnit
the time unit of the delay parameter
unit
)

Implements java.util.concurrent.ScheduledExecutorService.schedule.

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

public ScheduledFuture<?>
scheduleAtFixedRate(Runnable
the task to execute
command
,
long
the time to delay first execution
initialDelay
,
long
the period between successive executions
period
,
TimeUnit
the time unit of the initialDelay and period parameters
unit
)

Implements java.util.concurrent.ScheduledExecutorService.scheduleAtFixedRate.

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 initialDelay, then initialDelay + period, then initialDelay + 2 * period, and so on.

public ScheduledFuture<?>
scheduleWithFixedDelay(Runnable
the task to execute
command
,
long
the time to delay first execution
initialDelay
,
long
the delay between the termination of one execution and the commencement of the next
delay
,
TimeUnit
the time unit of the initialDelay and delay parameters
unit
)

Implements java.util.concurrent.ScheduledExecutorService.scheduleWithFixedDelay.

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.

public void
setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean
if true, continue after shutdown, else don't
value
)

Sets the policy on whether to continue executing existing periodic tasks even when this executor has been shutdown.

public void
setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean
if true, execute after shutdown, else don't
value
)

Sets the policy on whether to execute existing delayed tasks even when this executor has been shutdown.

public void
setRemoveOnCancelPolicy(boolean
if true, remove on cancellation, else don't
value
)

Sets the policy on whether cancelled tasks should be immediately removed from the work queue at time of cancellation.

public void
shutdown()

Overrides java.util.concurrent.ThreadPoolExecutor.shutdown.

Implements java.util.concurrent.ExecutorService.shutdown.

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

public List<Runnable>

Returns:

list of tasks that never commenced execution. Each element of this list is a ScheduledFuture. For tasks submitted via one of the schedule methods, the element will be identical to the returned ScheduledFuture. For tasks submitted using execute, the element will be a zero-delay ScheduledFuture.
shutdownNow
()

Overrides java.util.concurrent.ThreadPoolExecutor.shutdownNow.

Implements java.util.concurrent.ExecutorService.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.

public Future<?>
submit(Runnable
the task to submit
task
)

Overrides java.util.concurrent.AbstractExecutorService.submit.

Implements java.util.concurrent.ExecutorService.submit.

Submits a Runnable task for execution and returns a Future representing that task.

public <T> Future<T>
submit(Runnable
the task to submit
task
,
T
the result to return
result
)

Overrides java.util.concurrent.AbstractExecutorService.submit.

Implements java.util.concurrent.ExecutorService.submit.

Submits a Runnable task for execution and returns a Future representing that task.

public <T> Future<T>
submit(Callable<T>
the task to submit
task
)

Overrides java.util.concurrent.AbstractExecutorService.submit.

Implements java.util.concurrent.ExecutorService.submit.

Submits a value-returning task for execution and returns a Future representing the pending results of the task.

private long
triggerTime(long delay, TimeUnit unit)

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

pack-priv long
triggerTime(long delay)

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

Inherited from java.util.concurrent.ThreadPoolExecutor:
afterExecuteallowCoreThreadTimeOutallowsCoreThreadTimeOutawaitTerminationbeforeExecuteensurePrestartfinalizegetActiveCountgetCompletedTaskCountgetCorePoolSizegetKeepAliveTimegetLargestPoolSizegetMaximumPoolSizegetPoolSizegetRejectedExecutionHandlergetTaskCountgetThreadFactoryisShutdownisStoppedisTerminatedisTerminatingprestartAllCoreThreadsprestartCoreThreadpurgerejectremoverunWorkersetCorePoolSizesetKeepAliveTimesetMaximumPoolSizesetRejectedExecutionHandlersetThreadFactoryterminatedtoStringtryTerminate