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.
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.
}
Modifier and Type | Class and Description |
---|---|
pack-priv static class | ScheduledThreadPoolExecutor.
Specialized delay queue. |
private class |
Modifier and Type | Field 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. |
Access | Constructor and Description |
---|---|
public | ScheduledThreadPoolExecutor(int
the number of threads to keep in the pool, even
if they are idle, unless corePoolSize)allowCoreThreadTimeOut is setCreates a new |
public | ScheduledThreadPoolExecutor(int
the number of threads to keep in the pool, even
if they are idle, unless corePoolSize, ThreadFactory allowCoreThreadTimeOut is setthe factory to use when the executor
creates a new thread threadFactory)Creates a new |
public | ScheduledThreadPoolExecutor(int
the number of threads to keep in the pool, even
if they are idle, unless corePoolSize, RejectedExecutionHandler allowCoreThreadTimeOut is setthe handler to use when execution is blocked
because the thread bounds and queue capacities are reached handler)Creates a new |
public | ScheduledThreadPoolExecutor(int
the number of threads to keep in the pool, even
if they are idle, unless corePoolSize, ThreadFactory allowCoreThreadTimeOut is setthe 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 |
Modifier and Type | Method 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 | Returns: a task that can execute the runnablethe 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 | Returns: a task that can execute the callablethe 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. Implements java. Executes |
public boolean | Returns: true if will continue after shutdownGets the policy on whether to continue executing existing
periodic tasks even when this executor has been |
public boolean | Returns: true if will execute after shutdownGets the policy on whether to execute existing delayed
tasks even when this executor has been |
public BlockingQueue | Returns: the task queueOverrides java. Returns the task queue used by this executor. |
public boolean | Returns: true if cancelled tasks are immediately removed
from the queueGets the policy on whether cancelled tasks should be immediately removed from the work queue at time of cancellation. |
pack-priv void | onShutdown()
Overrides java. 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. Submits a one-shot task that becomes enabled after the given delay. |
public <V> ScheduledFuture | 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. 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. 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
|
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. 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 value)true , continue after shutdown, else don'tSets the policy on whether to continue executing existing
periodic tasks even when this executor has been |
public void | setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean
if value)true , execute after shutdown, else don'tSets the policy on whether to execute existing delayed
tasks even when this executor has been |
public void | setRemoveOnCancelPolicy(boolean
if value)true , remove on cancellation, else don'tSets the policy on whether cancelled tasks should be immediately removed from the work queue at time of cancellation. |
public void | shutdown()
Overrides java. Implements java. Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. |
public List | Returns: list of tasks that never commenced execution. Each element of this list is aScheduledFuture .
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 .Overrides java. Implements java. 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. Implements java. Submits a Runnable task for execution and returns a Future representing that task. |
public <T> Future | submit(Runnable
the task to submit task, T the result to return result)Overrides java. Implements java. Submits a Runnable task for execution and returns a Future representing that task. |
public <T> Future | submit(Callable<T>
the task to submit task)Overrides java. Implements java. Submits a value-returning task for execution and returns a Future representing the pending results of the task. |
private long | |
pack-priv long |