JDK1.6 ScheduledThreadPoolExecutor

介绍

ScheduledThreadPoolExecutor是一种类似Timer的定时器或者说是调度器。

优点

  1. 多线程的定时调度,timer是单线程的,每个timer实例只有一个工作线程。
  2. 由于继承自ThreadPoolExecutor,更具有灵活性和伸缩性。
  3. 没有timer那种线程泄露问题,timer调度的任务如果异常终止,那么整个timer都会被取消,无法执行其他任务。

源码分析

ScheduledExecutorService()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/**
* An {@link ExecutorService} that can schedule commands to run after a given
* delay, or to execute periodically.
*
* <p> The <tt>schedule</tt> methods create tasks with various delays
* and return a task object that can be used to cancel or check
* execution. The <tt>scheduleAtFixedRate</tt> and
* <tt>scheduleWithFixedDelay</tt> methods create and execute tasks
* that run periodically until cancelled.
*
* <p> Commands submitted using the {@link Executor#execute} and
* {@link ExecutorService} <tt>submit</tt> methods are scheduled with
* a requested delay of zero. Zero and negative delays (but not
* periods) are also allowed in <tt>schedule</tt> methods, and are
* treated as requests for immediate execution.
*
* .....
*
* @since 1.5
* @author Doug Lea
*/
public interface ScheduledExecutorService extends ExecutorService {

/**
* Creates and executes a one-shot action that becomes enabled
* after the given delay.
*
* @param command the task to execute
* @param delay the time from now to delay execution
* @param unit the time unit of the delay parameter
* @return a ScheduledFuture representing pending completion of
* the task and whose <tt>get()</tt> method will return
* <tt>null</tt> upon completion
* @throws RejectedExecutionException if the task cannot be
* scheduled for execution
* @throws NullPointerException if command is null
*/
// 1
public ScheduledFuture<?> schedule(Runnable command,
long delay, TimeUnit unit);

/**
* Creates and executes a ScheduledFuture that becomes enabled after the
* given delay.
*
* @param callable the function to execute
* @param delay the time from now to delay execution
* @param unit the time unit of the delay parameter
* @return a ScheduledFuture that can be used to extract result or cancel
* @throws RejectedExecutionException if the task cannot be
* scheduled for execution
* @throws NullPointerException if callable is null
*/
// 2
public <V> ScheduledFuture<V> schedule(Callable<V> callable,
long delay, TimeUnit unit);

/**
* Creates and executes a periodic action that becomes enabled first
* after the given initial delay, and subsequently with the given
* period; that is executions will commence after
* <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then
* <tt>initialDelay + 2 * period</tt>, and so on.
* If any execution of the task
* encounters an exception, subsequent executions are suppressed.
* Otherwise, the task will only terminate via cancellation or
* termination of the executor. If any execution of this task
* takes longer than its period, then subsequent executions
* may start late, but will not concurrently execute.
*
* @param command the task to execute
* @param initialDelay the time to delay first execution
* @param period the period between successive executions
* @param unit the time unit of the initialDelay and period parameters
* @return a ScheduledFuture representing pending completion of
* the task, and whose <tt>get()</tt> method will throw an
* exception upon cancellation
* @throws RejectedExecutionException if the task cannot be
* scheduled for execution
* @throws NullPointerException if command is null
* @throws IllegalArgumentException if period less than or equal to zero
*/
// 3
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);

/**
* Creates and executes 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. If any execution of the task
* encounters an exception, subsequent executions are suppressed.
* Otherwise, the task will only terminate via cancellation or
* termination of the executor.
*
* @param command the task to execute
* @param initialDelay the time to delay first execution
* @param delay the delay between the termination of one
* execution and the commencement of the next
* @param unit the time unit of the initialDelay and delay parameters
* @return a ScheduledFuture representing pending completion of
* the task, and whose <tt>get()</tt> method will throw an
* exception upon cancellation
* @throws RejectedExecutionException if the task cannot be
* scheduled for execution
* @throws NullPointerException if command is null
* @throws IllegalArgumentException if delay less than or equal to zero
*/
// 4
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit);

}

标注代码分析

  1. 创建并执行一个一次性任务,这个任务过了延迟时间就会被执行。
  2. 同上。Runnable变成callable。
  3. 创建并执行一个周期性任务,当任务过了给定的初始延迟时间,会第一次被执行,然后会以给定的周期时间执行。如果某次执行过程中发生异常,那么任务就停止了(不会执行下一次任务了)。如果某次执行时长超过了周期时间,那么下一次任务会延迟启动,不会和当前任务并行执行。
  4. 创建并执行一个周期性任务,当任务过了给定的初始延迟时间,会第一次被执行,接下来的任务会在上次任务执行完毕后,延迟给定的时间,然后再继续执行。如果某次执行过程中发生了异常,那么任务就停止了(不会执行下一次任务了)。

ScheduledThreadPoolExecutor#属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class ScheduledThreadPoolExecutor
extends ThreadPoolExecutor
implements ScheduledExecutorService {

/**
* False if should cancel/suppress periodic tasks on shutdown.
*/
// 1
private volatile boolean continueExistingPeriodicTasksAfterShutdown;

/**
* False if should cancel non-periodic tasks on shutdown.
*/
// 2
private volatile boolean executeExistingDelayedTasksAfterShutdown = true;

/**
* Sequence number to break scheduling ties, and in turn to
* guarantee FIFO order among tied entries.
*/
// 3
private static final AtomicLong sequencer = new AtomicLong(0);

/** Base of nanosecond timings, to avoid wrapping */
private static final long NANO_ORIGIN = System.nanoTime();
....

标注代码分析

  1. 是否应该在关闭时取消或者终止周期性任务。
  2. 是否应该在关闭时取消非周期性任务。
  3. 在并列调度(延迟值一样)的情况下保证先入先出的关系。

ScheduledThreadPoolExecutor()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Creates a new ScheduledThreadPoolExecutor with the given core
* pool size.
*
* @param corePoolSize the number of threads to keep in the pool,
* even if they are idle
* @throws IllegalArgumentException if <tt>corePoolSize &lt; 0</tt>
*/
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue());
}

/**
* Creates a new ScheduledThreadPoolExecutor with the given
* initial parameters.
*
* @param corePoolSize the number of threads to keep in the pool,
* even if they are idle
* @param threadFactory the factory to use when the executor
* creates a new thread
* @throws IllegalArgumentException if <tt>corePoolSize &lt; 0</tt>
* @throws NullPointerException if threadFactory is null
*/
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue(), threadFactory);
}

/**
* Creates a new ScheduledThreadPoolExecutor with the given
* initial parameters.
*
* @param corePoolSize the number of threads to keep in the pool,
* even if they are idle
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* @throws IllegalArgumentException if <tt>corePoolSize &lt; 0</tt>
* @throws NullPointerException if handler is null
*/
public ScheduledThreadPoolExecutor(int corePoolSize,
RejectedExecutionHandler handler) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue(), handler);
}

/**
* Creates a new ScheduledThreadPoolExecutor with the given
* initial parameters.
*
* @param corePoolSize the number of threads to keep in the pool,
* even if they are idle
* @param threadFactory the factory to use when the executor
* creates a new thread
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached.
* @throws IllegalArgumentException if <tt>corePoolSize &lt; 0</tt>
* @throws NullPointerException if threadFactory or handler is null
*/
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue(), threadFactory, handler);
}

从构造方法可以看出,ScheduledThreadPoolExecutor内部固定使用DelayedWorkQueue做为任务队列。

ScheduledThreadPoolExecutor#DelayedWorkQueue()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* An annoying wrapper class to convince javac to use a
* DelayQueue<RunnableScheduledFuture> as a BlockingQueue<Runnable>
*/
private static class DelayedWorkQueue
extends AbstractCollection<Runnable>
implements BlockingQueue<Runnable> {

private final DelayQueue<RunnableScheduledFuture> dq = new DelayQueue<RunnableScheduledFuture>();
public Runnable poll() { return dq.poll(); }
public Runnable peek() { return dq.peek(); }
public Runnable take() throws InterruptedException { return dq.take(); }
public Runnable poll(long timeout, TimeUnit unit) throws InterruptedException {
return dq.poll(timeout, unit);
}

public boolean add(Runnable x) {
return dq.add((RunnableScheduledFuture)x);
}
public boolean offer(Runnable x) {
return dq.offer((RunnableScheduledFuture)x);
}
public void put(Runnable x) {
dq.put((RunnableScheduledFuture)x);
}
public boolean offer(Runnable x, long timeout, TimeUnit unit) {
return dq.offer((RunnableScheduledFuture)x, timeout, unit);
}
....

DelayedWorkQueue内部就是一个DelayQueue,所有方法都由内部的DelayQueue来代理实现,唯一要注意的是进入队列的任务必须是RunnableScheduledFuture。再回头看ScheduledThreadPoolExecutor,因为延迟队列是无界的,所以最大线程数量也就没意义了。(ScheduledThreadPoolExecutor的最大线程数量是Integer.MAX_VALUE)

ScheduledThreadPoolExecutor#schedule()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public ScheduledFuture<?> schedule(Runnable command,
long delay,
TimeUnit unit) {
if (command == null || unit == null)
throw new NullPointerException();
// 1
RunnableScheduledFuture<?> t = decorateTask(command,
new ScheduledFutureTask<Void>(command, null,
triggerTime(delay, unit)));

// 2
delayedExecute(t);
return t;
}

public <V> ScheduledFuture<V> schedule(Callable<V> callable,
long delay,
TimeUnit unit) {
if (callable == null || unit == null)
throw new NullPointerException();
RunnableScheduledFuture<V> t = decorateTask(callable,
new ScheduledFutureTask<V>(callable,
triggerTime(delay, unit)));
delayedExecute(t);
return t;
}

标注代码分析

  1. 将任务包装成一个RunnableScheduledFuture。
  2. 然后延迟执行这个RunnableScheduledFuture。

ScheduledThreadPoolExecutor#triggerTime()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Returns the trigger time of a delayed action.
*/
// 1
private long triggerTime(long delay, TimeUnit unit) {
return triggerTime(unit.toNanos((delay < 0) ? 0 : delay));
}

/**
* Returns the trigger time of a delayed action.
*/
long triggerTime(long delay) {
// 2
return now() +
((delay < (Long.MAX_VALUE >> 1)) ? delay : overflowFree(delay));
}

标注代码分析

  1. 返回一个延迟动作的触发时间。
  2. 如果当前delay很大的话,要调用overflowFree来防止溢出。

ScheduledThreadPoolExecutor#overflowFree()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Constrains the values of all delays in the queue to be within
* Long.MAX_VALUE of each other, to avoid overflow in compareTo.
* This may occur if a task is eligible to be dequeued, but has
* not yet been, while some other task is added with a delay of
* Long.MAX_VALUE.
*/
private long overflowFree(long delay) {
Delayed head = (Delayed) super.getQueue().peek();
if (head != null) {
long headDelay = head.getDelay(TimeUnit.NANOSECONDS);
if (headDelay < 0 && (delay - headDelay < 0))
delay = Long.MAX_VALUE + headDelay;
}
return delay;
}

将队列中所有元素的延迟值彼此的和控制在Long.MAX_VALUE以内,避免在互相比较时溢出。这种情况是可能发生的,比如一个满足条件的任务即将出队,这时来一个延迟值是Long.MAX_VALUE的任务。

ScheduledThreadPoolExecutor#decorateTask()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* 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.
*
* @param runnable the submitted Runnable
* @param task the task created to execute the runnable
* @return a task that can execute the runnable
* @since 1.6
*/
protected <V> RunnableScheduledFuture<V> decorateTask(
Runnable runnable, RunnableScheduledFuture<V> task) {
return 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.
*
* @param callable the submitted Callable
* @param task the task created to execute the callable
* @return a task that can execute the callable
* @since 1.6
*/
protected <V> RunnableScheduledFuture<V> decorateTask(
Callable<V> callable, RunnableScheduledFuture<V> task) {
return task;
}

两个方法只是简单的实现,可作为钩子方法由子类实现。

ScheduledThreadPoolExecutor#ScheduledFutureTask

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
private class ScheduledFutureTask<V>
extends FutureTask<V> implements RunnableScheduledFuture<V> {

/** Sequence number to break ties FIFO */
// 1
private final long sequenceNumber;
/** The time the task is enabled to execute in nanoTime units */
// 2
private long time;
/**
* Period in nanoseconds for repeating tasks. A positive
* value indicates fixed-rate execution. A negative value
* indicates fixed-delay execution. A value of 0 indicates a
* non-repeating task.
*/
// 3
private final long period;

/**
* Creates a one-shot action with given nanoTime-based trigger time.
*/
ScheduledFutureTask(Runnable r, V result, long ns) {
super(r, result);
this.time = ns;
this.period = 0;
this.sequenceNumber = sequencer.getAndIncrement();
}

/**
* Creates a periodic action with given nano time and period.
*/
ScheduledFutureTask(Runnable r, V result, long ns, long period) {
super(r, result);
this.time = ns;
this.period = period;
this.sequenceNumber = sequencer.getAndIncrement();
}

/**
* Creates a one-shot action with given nanoTime-based trigger.
*/
ScheduledFutureTask(Callable<V> callable, long ns) {
super(callable);
this.time = ns;
this.period = 0;
this.sequenceNumber = sequencer.getAndIncrement();
}
....

ScheduledFutureTask实现RunnableScheduledFuture。
标注代码分析

  1. 任务序列号
  2. 任务可以执行的时间,单位纳秒
  3. 周期性任务的周期时间,单位纳秒。正数表示固定频率执行,负数表示固定延迟执行,0表示一次性任务。

RunnableScheduledFuture

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* A {@link ScheduledFuture} that is {@link Runnable}. Successful
* execution of the <tt>run</tt> method causes completion of the
* <tt>Future</tt> and allows access to its results.
* @see FutureTask
* @see Executor
* @since 1.6
* @author Doug Lea
* @param <V> The result type returned by this Future's <tt>get</tt> method
*/
public interface RunnableScheduledFuture<V> extends RunnableFuture<V>, ScheduledFuture<V> {

/**
* Returns true if this is a periodic task. A periodic task may
* re-run according to some schedule. A non-periodic task can be
* run only once.
*
* @return true if this task is periodic
*/
// 1
boolean isPeriodic();
}

标注代码分析

  1. 是否为周期性任务。

ScheduledThreadPoolExecutor#ScheduledFutureTask#getDelay()

1
2
3
4
// 1
public long getDelay(TimeUnit unit) {
return unit.convert(time - now(), TimeUnit.NANOSECONDS);
}

标注代码分析

  1. 延迟值都是按照纳秒时间单位来算的。这里减去了now(),还记得之前算触发时间时候加上now()。

    ScheduledThreadPoolExecutor#ScheduledFutureTask#compareTo()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public int compareTo(Delayed other) {
    if (other == this) // compare zero ONLY if same object
    return 0;
    if (other instanceof ScheduledFutureTask) {
    ScheduledFutureTask<?> x = (ScheduledFutureTask<?>)other;
    long diff = time - x.time;
    if (diff < 0)
    return -1;
    else if (diff > 0)
    return 1;
    else if (sequenceNumber < x.sequenceNumber)// 1
    return -1;
    else
    return 1;
    }
    // 2
    long d = (getDelay(TimeUnit.NANOSECONDS) -
    other.getDelay(TimeUnit.NANOSECONDS));
    return (d == 0)? 0 : ((d < 0)? -1 : 1);
    }

标注代码分析

  1. 如果触发时间相等,那么比较序列号,从而保证顺序。
  2. 如果要比较的对象不是ScheduledFutureTask,那么按照延迟值进行比较。

ScheduledThreadPoolExecutor#getQueue()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* Returns the task queue used by this executor. Each element of
* this queue is a {@link ScheduledFuture}, including those
* tasks submitted using <tt>execute</tt> which are for scheduling
* purposes used as the basis of a zero-delay
* <tt>ScheduledFuture</tt>. Iteration over this queue is
* <em>not</em> guaranteed to traverse tasks in the order in
* which they will execute.
*
* @return the task queue
*/
public BlockingQueue<Runnable> getQueue() {
return super.getQueue();
}

通过getDelay()实现延迟计算。overflowFree()通过Delayed head = (Delayed) super.getQueue().peek();获取延迟对象。getQueue()新增是runnable对象。

ScheduledThreadPoolExecutor#delayedExecute()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Specialized variant of ThreadPoolExecutor.execute for delayed tasks.
*/
private void delayedExecute(Runnable command) {
if (isShutdown()) {
// 1
reject(command);
return;
}
// Prestart a thread if necessary. We cannot prestart it
// running the task because the task (probably) shouldn't be
// run yet, so thread will just idle until delay elapses.
// 2
if (getPoolSize() < getCorePoolSize())
prestartCoreThread();
// 3
super.getQueue().add(command);
}

标注代码分析

  1. 如果当前ScheduledThreadPoolExecutor已关闭,拒绝任务。
  2. 如果当前线程数量小于核心线程数量,那么预启动一个核心线程。
  3. 将任务加入任务队列。

ScheduledThreadPoolExecutor#ScheduledFutureTask#delayedExecute()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Runs a periodic task.
*/
private void runPeriodic() {
boolean ok = ScheduledFutureTask.super.runAndReset();
boolean down = isShutdown();
// Reschedule if not cancelled and not shutdown or policy allows
if (ok && (!down ||
(getContinueExistingPeriodicTasksAfterShutdownPolicy() &&
!isStopped()))) {
long p = period;
if (p > 0)
time += p;
else
time = triggerTime(-p);
ScheduledThreadPoolExecutor.super.getQueue().add(this);
}
// This might have been the final executed delayed
// task. Wake up threads to check.
else if (down)
interruptIdleWorkers();
}

由ScheduledThreadPoolExecutor#delayedExecute()、ScheduledThreadPoolExecutor#delayedExecute()可以知道,getQueue()队列里添加的是ScheduledFutureTask对象。根据ScheduledFutureTask实现RunnableScheduledFuture,RunnableScheduledFuture继承ScheduledFuture,ScheduledFuture继承Delayed(延迟),我们知道ScheduledThreadPoolExecutor内部使用延迟队列。如下图。

ScheduledThreadPoolExecutor#ScheduledFutureTask#run()

1
2
3
4
5
6
7
8
9
10
11
12
/**
* Overrides FutureTask version so as to reset/requeue if periodic.
*/
public void run() {
// 1
if (isPeriodic())
// 2
runPeriodic();
else
// 3
ScheduledFutureTask.super.run();
}

标注代码分析

  1. 判断下当前任务是否为周期任务。
  2. 如果是周期任务,按照周期任务方式运行。
  3. 一次性任务的话,就直接执行run方法。

ScheduledThreadPoolExecutor#ScheduledFutureTask#runPeriodic()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Runs a periodic task.
*/
private void runPeriodic() {
// 1
boolean ok = ScheduledFutureTask.super.runAndReset();
// 2
boolean down = isShutdown();
// Reschedule if not cancelled and not shutdown or policy allows
// 3
if (ok && (!down ||
(getContinueExistingPeriodicTasksAfterShutdownPolicy() &&
!isStopped()))) {
// 4
long p = period;
if (p > 0)
// 5
time += p;
else
// 6
time = triggerTime(-p);
// 7
ScheduledThreadPoolExecutor.super.getQueue().add(this);
}
// This might have been the final executed delayed
// task. Wake up threads to check.
// 8
else if (down)
interruptIdleWorkers();
}

标注代码分析

  1. 这里执行任务并重置异步任务。
  2. 判断当前ScheduledThreadPoolExecutor是否关闭。
  3. 如果任务执行成功,并且ScheduledThreadPoolExecutor没有关闭或者策略允许关闭后继续执行周期任务,并且ScheduledThreadPoolExecutor没有停止,那么重新调度任务。
  4. 重新计算下次触发时间。
  5. 如果是固定频率,在原有触发时间上加上周期时间。
  6. 如果是固定延迟,直接指定延迟后的触发时间。
  7. 算好下次触发时间后,再将任务本身重新加入任务队列。
  8. 这可能是最后执行的延迟任务。执行完毕后,如果当前ScheduledThreadPoolExecutor已关闭,那么中断空闲的工作线程。

ScheduledThreadPoolExecutor#scheduleAtFixedRate()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit) {
if (command == null || unit == null)
throw new NullPointerException();
if (period <= 0)
throw new IllegalArgumentException();
RunnableScheduledFuture<?> t = decorateTask(command,
new ScheduledFutureTask<Object>(command,
null,
triggerTime(initialDelay, unit),
unit.toNanos(period)));
delayedExecute(t);
return t;
}

ScheduledThreadPoolExecutor#scheduleWithFixedDelay()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit) {
if (command == null || unit == null)
throw new NullPointerException();
if (delay <= 0)
throw new IllegalArgumentException();
RunnableScheduledFuture<?> t = decorateTask(command,
new ScheduledFutureTask<Boolean>(command,
null,
triggerTime(initialDelay, unit),
unit.toNanos(-delay)));
delayedExecute(t);
return t;
}

通过包装ScheduledFutureTask对象生成RunnableScheduledFuture对象。然后再执行任务。
2个方法区别在第4个参数。unit.toNanos(-delay)和TimeUnit unit。负数表示固定延迟周期性任务。

ScheduledThreadPoolExecutor#setContinueExistingPeriodicTasksAfterShutdownPolicy()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Sets the policy on whether to continue executing existing periodic
* tasks even when this executor has been <tt>shutdown</tt>. In
* this case, these tasks will only terminate upon
* <tt>shutdownNow</tt>, or after setting the policy to
* <tt>false</tt> when already shutdown. This value is by default
* false.
*
* @param value if true, continue after shutdown, else don't.
* @see #getContinueExistingPeriodicTasksAfterShutdownPolicy
*/
public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value) {
continueExistingPeriodicTasksAfterShutdown = value;
if (!value && isShutdown())
cancelUnwantedTasks();
}

ScheduledThreadPoolExecutor#setExecuteExistingDelayedTasksAfterShutdownPolicy()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Sets the policy on whether to execute existing delayed
* tasks even when this executor has been <tt>shutdown</tt>. In
* this case, these tasks will only terminate upon
* <tt>shutdownNow</tt>, or after setting the policy to
* <tt>false</tt> when already shutdown. This value is by default
* true.
*
* @param value if true, execute after shutdown, else don't.
* @see #getExecuteExistingDelayedTasksAfterShutdownPolicy
*/
public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value) {
executeExistingDelayedTasksAfterShutdown = value;
if (!value && isShutdown())
cancelUnwantedTasks();
}

ScheduledThreadPoolExecutor#shutdown()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* Initiates an orderly shutdown in which previously submitted
* tasks are executed, but no new tasks will be accepted. If the
* <tt>ExecuteExistingDelayedTasksAfterShutdownPolicy</tt> has
* been set <tt>false</tt>, existing delayed tasks whose delays
* have not yet elapsed are cancelled. And unless the
* <tt>ContinueExistingPeriodicTasksAfterShutdownPolicy</tt> has
* been set <tt>true</tt>, future executions of existing periodic
* tasks will be cancelled.
*/
public void shutdown() {
cancelUnwantedTasks();
super.shutdown();
}

ScheduledThreadPoolExecutor#cancelUnwantedTasks()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Cancels and clears the queue of all tasks that should not be run
* due to shutdown policy.
*/
private void cancelUnwantedTasks() {
// 1
boolean keepDelayed = getExecuteExistingDelayedTasksAfterShutdownPolicy();
// 2
boolean keepPeriodic = getContinueExistingPeriodicTasksAfterShutdownPolicy();
if (!keepDelayed && !keepPeriodic)
// 3
super.getQueue().clear();
else if (keepDelayed || keepPeriodic) {
// 4
Object[] entries = super.getQueue().toArray();
for (int i = 0; i < entries.length; ++i) {
Object e = entries[i];
if (e instanceof RunnableScheduledFuture) {
RunnableScheduledFuture<?> t = (RunnableScheduledFuture<?>)e;
if (t.isPeriodic()? !keepPeriodic : !keepDelayed)
t.cancel(false);
}
}
entries = null;
// 5
purge();
}
}

标注代码分析

  1. 关闭后是否继续执行延迟的任务。
  2. 关闭后是否继续执行周期性的任务。
  3. 如果都不继续,那么直接清空任务队列。
  4. 否则会按照相应的策略来取消相应类型的任务。
  5. 最后清理一把任务队列里面被取消的任务。

可以看到在设置关闭后任务处理策略和关闭当前ScheduledThreadPoolExecutor时,都会(按需)调用一下cancelUnwantedTasks方法来清理不需要的任务。

总结

  1. ScheduledFutureTask表示可调度的异步任务,提交到ScheduledThreadPoolExecutor的任务都会被包装成这个类。
  2. ScheduledThreadPoolExecutor调度任务时会按照延迟时间来,延迟时间最先到期的任务会被首先调度,如果两个任务延迟时间相同,那么还有内部序列号来保证先入先出的顺序。
  3. ScheduledFutureTask被调度后,具体执行时,会判断自己是否是周期性任务。如果不是,任务执行一次;如果时,先执行任务,执行成功后,会算出下次触发事件(延迟时间),然后被再次放入ScheduledThreadPoolExecutor的任务队列中,等待下次被调度执行。

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×