1. /*
  2. * @(#)ScheduledThreadPoolExecutor.java 1.3 04/04/14
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util.concurrent;
  8. import java.util.concurrent.atomic.*;
  9. import java.util.*;
  10. /**
  11. * A {@link ThreadPoolExecutor} that can additionally schedule
  12. * commands to run after a given delay, or to execute
  13. * periodically. This class is preferable to {@link java.util.Timer}
  14. * when multiple worker threads are needed, or when the additional
  15. * flexibility or capabilities of {@link ThreadPoolExecutor} (which
  16. * this class extends) are required.
  17. *
  18. * <p> Delayed tasks execute no sooner than they are enabled, but
  19. * without any real-time guarantees about when, after they are
  20. * enabled, they will commence. Tasks scheduled for exactly the same
  21. * execution time are enabled in first-in-first-out (FIFO) order of
  22. * submission.
  23. *
  24. * <p>While this class inherits from {@link ThreadPoolExecutor}, a few
  25. * of the inherited tuning methods are not useful for it. In
  26. * particular, because it acts as a fixed-sized pool using
  27. * <tt>corePoolSize</tt> threads and an unbounded queue, adjustments
  28. * to <tt>maximumPoolSize</tt> have no useful effect.
  29. *
  30. * @since 1.5
  31. * @author Doug Lea
  32. */
  33. public class ScheduledThreadPoolExecutor
  34. extends ThreadPoolExecutor
  35. implements ScheduledExecutorService {
  36. /**
  37. * False if should cancel/suppress periodic tasks on shutdown.
  38. */
  39. private volatile boolean continueExistingPeriodicTasksAfterShutdown;
  40. /**
  41. * False if should cancel non-periodic tasks on shutdown.
  42. */
  43. private volatile boolean executeExistingDelayedTasksAfterShutdown = true;
  44. /**
  45. * Sequence number to break scheduling ties, and in turn to
  46. * guarantee FIFO order among tied entries.
  47. */
  48. private static final AtomicLong sequencer = new AtomicLong(0);
  49. /** Base of nanosecond timings, to avoid wrapping */
  50. private static final long NANO_ORIGIN = System.nanoTime();
  51. /**
  52. * Returns nanosecond time offset by origin
  53. */
  54. final long now() {
  55. return System.nanoTime() - NANO_ORIGIN;
  56. }
  57. private class ScheduledFutureTask<V>
  58. extends FutureTask<V> implements ScheduledFuture<V> {
  59. /** Sequence number to break ties FIFO */
  60. private final long sequenceNumber;
  61. /** The time the task is enabled to execute in nanoTime units */
  62. private long time;
  63. /**
  64. * Period in nanoseconds for repeating tasks. A positive
  65. * value indicates fixed-rate execution. A negative value
  66. * indicates fixed-delay execution. A value of 0 indicates a
  67. * non-repeating task.
  68. */
  69. private final long period;
  70. /**
  71. * Creates a one-shot action with given nanoTime-based trigger time
  72. */
  73. ScheduledFutureTask(Runnable r, V result, long ns) {
  74. super(r, result);
  75. this.time = ns;
  76. this.period = 0;
  77. this.sequenceNumber = sequencer.getAndIncrement();
  78. }
  79. /**
  80. * Creates a periodic action with given nano time and period
  81. */
  82. ScheduledFutureTask(Runnable r, V result, long ns, long period) {
  83. super(r, result);
  84. this.time = ns;
  85. this.period = period;
  86. this.sequenceNumber = sequencer.getAndIncrement();
  87. }
  88. /**
  89. * Creates a one-shot action with given nanoTime-based trigger
  90. */
  91. ScheduledFutureTask(Callable<V> callable, long ns) {
  92. super(callable);
  93. this.time = ns;
  94. this.period = 0;
  95. this.sequenceNumber = sequencer.getAndIncrement();
  96. }
  97. public long getDelay(TimeUnit unit) {
  98. long d = unit.convert(time - now(), TimeUnit.NANOSECONDS);
  99. return d;
  100. }
  101. public int compareTo(Delayed other) {
  102. if (other == this) // compare zero ONLY if same object
  103. return 0;
  104. ScheduledFutureTask<?> x = (ScheduledFutureTask<?>)other;
  105. long diff = time - x.time;
  106. if (diff < 0)
  107. return -1;
  108. else if (diff > 0)
  109. return 1;
  110. else if (sequenceNumber < x.sequenceNumber)
  111. return -1;
  112. else
  113. return 1;
  114. }
  115. /**
  116. * Returns true if this is a periodic (not a one-shot) action.
  117. * @return true if periodic
  118. */
  119. boolean isPeriodic() {
  120. return period != 0;
  121. }
  122. /**
  123. * Run a periodic task
  124. */
  125. private void runPeriodic() {
  126. boolean ok = ScheduledFutureTask.super.runAndReset();
  127. boolean down = isShutdown();
  128. // Reschedule if not cancelled and not shutdown or policy allows
  129. if (ok && (!down ||
  130. (getContinueExistingPeriodicTasksAfterShutdownPolicy() &&
  131. !isTerminating()))) {
  132. long p = period;
  133. if (p > 0)
  134. time += p;
  135. else
  136. time = now() - p;
  137. ScheduledThreadPoolExecutor.super.getQueue().add(this);
  138. }
  139. // This might have been the final executed delayed
  140. // task. Wake up threads to check.
  141. else if (down)
  142. interruptIdleWorkers();
  143. }
  144. /**
  145. * Overrides FutureTask version so as to reset/requeue if periodic.
  146. */
  147. public void run() {
  148. if (isPeriodic())
  149. runPeriodic();
  150. else
  151. ScheduledFutureTask.super.run();
  152. }
  153. }
  154. /**
  155. * Specialized variant of ThreadPoolExecutor.execute for delayed tasks.
  156. */
  157. private void delayedExecute(Runnable command) {
  158. if (isShutdown()) {
  159. reject(command);
  160. return;
  161. }
  162. // Prestart a thread if necessary. We cannot prestart it
  163. // running the task because the task (probably) shouldn't be
  164. // run yet, so thread will just idle until delay elapses.
  165. if (getPoolSize() < getCorePoolSize())
  166. prestartCoreThread();
  167. super.getQueue().add(command);
  168. }
  169. /**
  170. * Cancel and clear the queue of all tasks that should not be run
  171. * due to shutdown policy.
  172. */
  173. private void cancelUnwantedTasks() {
  174. boolean keepDelayed = getExecuteExistingDelayedTasksAfterShutdownPolicy();
  175. boolean keepPeriodic = getContinueExistingPeriodicTasksAfterShutdownPolicy();
  176. if (!keepDelayed && !keepPeriodic)
  177. super.getQueue().clear();
  178. else if (keepDelayed || keepPeriodic) {
  179. Object[] entries = super.getQueue().toArray();
  180. for (int i = 0; i < entries.length; ++i) {
  181. Object e = entries[i];
  182. if (e instanceof ScheduledFutureTask) {
  183. ScheduledFutureTask<?> t = (ScheduledFutureTask<?>)e;
  184. if (t.isPeriodic()? !keepPeriodic : !keepDelayed)
  185. t.cancel(false);
  186. }
  187. }
  188. entries = null;
  189. purge();
  190. }
  191. }
  192. public boolean remove(Runnable task) {
  193. if (!(task instanceof ScheduledFutureTask))
  194. return false;
  195. return getQueue().remove(task);
  196. }
  197. /**
  198. * Creates a new ScheduledThreadPoolExecutor with the given core
  199. * pool size.
  200. *
  201. * @param corePoolSize the number of threads to keep in the pool,
  202. * even if they are idle.
  203. * @throws IllegalArgumentException if corePoolSize less than or
  204. * equal to zero
  205. */
  206. public ScheduledThreadPoolExecutor(int corePoolSize) {
  207. super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
  208. new DelayedWorkQueue());
  209. }
  210. /**
  211. * Creates a new ScheduledThreadPoolExecutor with the given
  212. * initial parameters.
  213. *
  214. * @param corePoolSize the number of threads to keep in the pool,
  215. * even if they are idle.
  216. * @param threadFactory the factory to use when the executor
  217. * creates a new thread.
  218. * @throws NullPointerException if threadFactory is null
  219. */
  220. public ScheduledThreadPoolExecutor(int corePoolSize,
  221. ThreadFactory threadFactory) {
  222. super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
  223. new DelayedWorkQueue(), threadFactory);
  224. }
  225. /**
  226. * Creates a new ScheduledThreadPoolExecutor with the given
  227. * initial parameters.
  228. *
  229. * @param corePoolSize the number of threads to keep in the pool,
  230. * even if they are idle.
  231. * @param handler the handler to use when execution is blocked
  232. * because the thread bounds and queue capacities are reached.
  233. * @throws NullPointerException if handler is null
  234. */
  235. public ScheduledThreadPoolExecutor(int corePoolSize,
  236. RejectedExecutionHandler handler) {
  237. super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
  238. new DelayedWorkQueue(), handler);
  239. }
  240. /**
  241. * Creates a new ScheduledThreadPoolExecutor with the given
  242. * initial parameters.
  243. *
  244. * @param corePoolSize the number of threads to keep in the pool,
  245. * even if they are idle.
  246. * @param threadFactory the factory to use when the executor
  247. * creates a new thread.
  248. * @param handler the handler to use when execution is blocked
  249. * because the thread bounds and queue capacities are reached.
  250. * @throws NullPointerException if threadFactory or handler is null
  251. */
  252. public ScheduledThreadPoolExecutor(int corePoolSize,
  253. ThreadFactory threadFactory,
  254. RejectedExecutionHandler handler) {
  255. super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
  256. new DelayedWorkQueue(), threadFactory, handler);
  257. }
  258. public ScheduledFuture<?> schedule(Runnable command,
  259. long delay,
  260. TimeUnit unit) {
  261. if (command == null || unit == null)
  262. throw new NullPointerException();
  263. long triggerTime = now() + unit.toNanos(delay);
  264. ScheduledFutureTask<?> t =
  265. new ScheduledFutureTask<Boolean>(command, null, triggerTime);
  266. delayedExecute(t);
  267. return t;
  268. }
  269. public <V> ScheduledFuture<V> schedule(Callable<V> callable,
  270. long delay,
  271. TimeUnit unit) {
  272. if (callable == null || unit == null)
  273. throw new NullPointerException();
  274. if (delay < 0) delay = 0;
  275. long triggerTime = now() + unit.toNanos(delay);
  276. ScheduledFutureTask<V> t =
  277. new ScheduledFutureTask<V>(callable, triggerTime);
  278. delayedExecute(t);
  279. return t;
  280. }
  281. public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
  282. long initialDelay,
  283. long period,
  284. TimeUnit unit) {
  285. if (command == null || unit == null)
  286. throw new NullPointerException();
  287. if (period <= 0)
  288. throw new IllegalArgumentException();
  289. if (initialDelay < 0) initialDelay = 0;
  290. long triggerTime = now() + unit.toNanos(initialDelay);
  291. ScheduledFutureTask<?> t =
  292. new ScheduledFutureTask<Object>(command,
  293. null,
  294. triggerTime,
  295. unit.toNanos(period));
  296. delayedExecute(t);
  297. return t;
  298. }
  299. public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
  300. long initialDelay,
  301. long delay,
  302. TimeUnit unit) {
  303. if (command == null || unit == null)
  304. throw new NullPointerException();
  305. if (delay <= 0)
  306. throw new IllegalArgumentException();
  307. if (initialDelay < 0) initialDelay = 0;
  308. long triggerTime = now() + unit.toNanos(initialDelay);
  309. ScheduledFutureTask<?> t =
  310. new ScheduledFutureTask<Boolean>(command,
  311. null,
  312. triggerTime,
  313. unit.toNanos(-delay));
  314. delayedExecute(t);
  315. return t;
  316. }
  317. /**
  318. * Execute command with zero required delay. This has effect
  319. * equivalent to <tt>schedule(command, 0, anyUnit)</tt>. Note
  320. * that inspections of the queue and of the list returned by
  321. * <tt>shutdownNow</tt> will access the zero-delayed
  322. * {@link ScheduledFuture}, not the <tt>command</tt> itself.
  323. *
  324. * @param command the task to execute
  325. * @throws RejectedExecutionException at discretion of
  326. * <tt>RejectedExecutionHandler</tt>, if task cannot be accepted
  327. * for execution because the executor has been shut down.
  328. * @throws NullPointerException if command is null
  329. */
  330. public void execute(Runnable command) {
  331. if (command == null)
  332. throw new NullPointerException();
  333. schedule(command, 0, TimeUnit.NANOSECONDS);
  334. }
  335. // Override AbstractExecutorService methods
  336. public Future<?> submit(Runnable task) {
  337. return schedule(task, 0, TimeUnit.NANOSECONDS);
  338. }
  339. public <T> Future<T> submit(Runnable task, T result) {
  340. return schedule(Executors.callable(task, result),
  341. 0, TimeUnit.NANOSECONDS);
  342. }
  343. public <T> Future<T> submit(Callable<T> task) {
  344. return schedule(task, 0, TimeUnit.NANOSECONDS);
  345. }
  346. /**
  347. * Set policy on whether to continue executing existing periodic
  348. * tasks even when this executor has been <tt>shutdown</tt>. In
  349. * this case, these tasks will only terminate upon
  350. * <tt>shutdownNow</tt>, or after setting the policy to
  351. * <tt>false</tt> when already shutdown. This value is by default
  352. * false.
  353. * @param value if true, continue after shutdown, else don't.
  354. * @see #getExecuteExistingDelayedTasksAfterShutdownPolicy
  355. */
  356. public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value) {
  357. continueExistingPeriodicTasksAfterShutdown = value;
  358. if (!value && isShutdown())
  359. cancelUnwantedTasks();
  360. }
  361. /**
  362. * Get the policy on whether to continue executing existing
  363. * periodic tasks even when this executor has been
  364. * <tt>shutdown</tt>. In this case, these tasks will only
  365. * terminate upon <tt>shutdownNow</tt> or after setting the policy
  366. * to <tt>false</tt> when already shutdown. This value is by
  367. * default false.
  368. * @return true if will continue after shutdown.
  369. * @see #setContinueExistingPeriodicTasksAfterShutdownPolicy
  370. */
  371. public boolean getContinueExistingPeriodicTasksAfterShutdownPolicy() {
  372. return continueExistingPeriodicTasksAfterShutdown;
  373. }
  374. /**
  375. * Set policy on whether to execute existing delayed
  376. * tasks even when this executor has been <tt>shutdown</tt>. In
  377. * this case, these tasks will only terminate upon
  378. * <tt>shutdownNow</tt>, or after setting the policy to
  379. * <tt>false</tt> when already shutdown. This value is by default
  380. * true.
  381. * @param value if true, execute after shutdown, else don't.
  382. * @see #getExecuteExistingDelayedTasksAfterShutdownPolicy
  383. */
  384. public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value) {
  385. executeExistingDelayedTasksAfterShutdown = value;
  386. if (!value && isShutdown())
  387. cancelUnwantedTasks();
  388. }
  389. /**
  390. * Get policy on whether to execute existing delayed
  391. * tasks even when this executor has been <tt>shutdown</tt>. In
  392. * this case, these tasks will only terminate upon
  393. * <tt>shutdownNow</tt>, or after setting the policy to
  394. * <tt>false</tt> when already shutdown. This value is by default
  395. * true.
  396. * @return true if will execute after shutdown.
  397. * @see #setExecuteExistingDelayedTasksAfterShutdownPolicy
  398. */
  399. public boolean getExecuteExistingDelayedTasksAfterShutdownPolicy() {
  400. return executeExistingDelayedTasksAfterShutdown;
  401. }
  402. /**
  403. * Initiates an orderly shutdown in which previously submitted
  404. * tasks are executed, but no new tasks will be accepted. If the
  405. * <tt>ExecuteExistingDelayedTasksAfterShutdownPolicy</tt> has
  406. * been set <tt>false</tt>, existing delayed tasks whose delays
  407. * have not yet elapsed are cancelled. And unless the
  408. * <tt>ContinueExistingPeriodicTasksAfterShutdownPolicy</tt> has
  409. * been set <tt>true</tt>, future executions of existing periodic
  410. * tasks will be cancelled.
  411. */
  412. public void shutdown() {
  413. cancelUnwantedTasks();
  414. super.shutdown();
  415. }
  416. /**
  417. * Attempts to stop all actively executing tasks, halts the
  418. * processing of waiting tasks, and returns a list of the tasks that were
  419. * awaiting execution.
  420. *
  421. * <p>There are no guarantees beyond best-effort attempts to stop
  422. * processing actively executing tasks. This implementation
  423. * cancels tasks via {@link Thread#interrupt}, so if any tasks mask or
  424. * fail to respond to interrupts, they may never terminate.
  425. *
  426. * @return list of tasks that never commenced execution. Each
  427. * element of this list is a {@link ScheduledFuture},
  428. * including those tasks submitted using <tt>execute</tt>, which
  429. * are for scheduling purposes used as the basis of a zero-delay
  430. * <tt>ScheduledFuture</tt>.
  431. */
  432. public List<Runnable> shutdownNow() {
  433. return super.shutdownNow();
  434. }
  435. /**
  436. * Returns the task queue used by this executor. Each element of
  437. * this queue is a {@link ScheduledFuture}, including those
  438. * tasks submitted using <tt>execute</tt> which are for scheduling
  439. * purposes used as the basis of a zero-delay
  440. * <tt>ScheduledFuture</tt>. Iteration over this queue is
  441. * <em>not</em> guaranteed to traverse tasks in the order in
  442. * which they will execute.
  443. *
  444. * @return the task queue
  445. */
  446. public BlockingQueue<Runnable> getQueue() {
  447. return super.getQueue();
  448. }
  449. /**
  450. * An annoying wrapper class to convince generics compiler to
  451. * use a DelayQueue<ScheduledFutureTask> as a BlockingQueue<Runnable>
  452. */
  453. private static class DelayedWorkQueue
  454. extends AbstractCollection<Runnable>
  455. implements BlockingQueue<Runnable> {
  456. private final DelayQueue<ScheduledFutureTask> dq = new DelayQueue<ScheduledFutureTask>();
  457. public Runnable poll() { return dq.poll(); }
  458. public Runnable peek() { return dq.peek(); }
  459. public Runnable take() throws InterruptedException { return dq.take(); }
  460. public Runnable poll(long timeout, TimeUnit unit) throws InterruptedException {
  461. return dq.poll(timeout, unit);
  462. }
  463. public boolean add(Runnable x) { return dq.add((ScheduledFutureTask)x); }
  464. public boolean offer(Runnable x) { return dq.offer((ScheduledFutureTask)x); }
  465. public void put(Runnable x) {
  466. dq.put((ScheduledFutureTask)x);
  467. }
  468. public boolean offer(Runnable x, long timeout, TimeUnit unit) {
  469. return dq.offer((ScheduledFutureTask)x, timeout, unit);
  470. }
  471. public Runnable remove() { return dq.remove(); }
  472. public Runnable element() { return dq.element(); }
  473. public void clear() { dq.clear(); }
  474. public int drainTo(Collection<? super Runnable> c) { return dq.drainTo(c); }
  475. public int drainTo(Collection<? super Runnable> c, int maxElements) {
  476. return dq.drainTo(c, maxElements);
  477. }
  478. public int remainingCapacity() { return dq.remainingCapacity(); }
  479. public boolean remove(Object x) { return dq.remove(x); }
  480. public boolean contains(Object x) { return dq.contains(x); }
  481. public int size() { return dq.size(); }
  482. public boolean isEmpty() { return dq.isEmpty(); }
  483. public Object[] toArray() { return dq.toArray(); }
  484. public <T> T[] toArray(T[] array) { return dq.toArray(array); }
  485. public Iterator<Runnable> iterator() {
  486. return new Iterator<Runnable>() {
  487. private Iterator<ScheduledFutureTask> it = dq.iterator();
  488. public boolean hasNext() { return it.hasNext(); }
  489. public Runnable next() { return it.next(); }
  490. public void remove() { it.remove(); }
  491. };
  492. }
  493. }
  494. }