1. /*
  2. * @(#)Timer.java 1.17 04/04/12
  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;
  8. import java.util.Date;
  9. /**
  10. * A facility for threads to schedule tasks for future execution in a
  11. * background thread. Tasks may be scheduled for one-time execution, or for
  12. * repeated execution at regular intervals.
  13. *
  14. * <p>Corresponding to each <tt>Timer</tt> object is a single background
  15. * thread that is used to execute all of the timer's tasks, sequentially.
  16. * Timer tasks should complete quickly. If a timer task takes excessive time
  17. * to complete, it "hogs" the timer's task execution thread. This can, in
  18. * turn, delay the execution of subsequent tasks, which may "bunch up" and
  19. * execute in rapid succession when (and if) the offending task finally
  20. * completes.
  21. *
  22. * <p>After the last live reference to a <tt>Timer</tt> object goes away
  23. * <i>and</i> all outstanding tasks have completed execution, the timer's task
  24. * execution thread terminates gracefully (and becomes subject to garbage
  25. * collection). However, this can take arbitrarily long to occur. By
  26. * default, the task execution thread does not run as a <i>daemon thread</i>,
  27. * so it is capable of keeping an application from terminating. If a caller
  28. * wants to terminate a timer's task execution thread rapidly, the caller
  29. * should invoke the timer's <tt>cancel</tt> method.
  30. *
  31. * <p>If the timer's task execution thread terminates unexpectedly, for
  32. * example, because its <tt>stop</tt> method is invoked, any further
  33. * attempt to schedule a task on the timer will result in an
  34. * <tt>IllegalStateException</tt>, as if the timer's <tt>cancel</tt>
  35. * method had been invoked.
  36. *
  37. * <p>This class is thread-safe: multiple threads can share a single
  38. * <tt>Timer</tt> object without the need for external synchronization.
  39. *
  40. * <p>This class does <i>not</i> offer real-time guarantees: it schedules
  41. * tasks using the <tt>Object.wait(long)</tt> method.
  42. *
  43. * <p>Implementation note: This class scales to large numbers of concurrently
  44. * scheduled tasks (thousands should present no problem). Internally,
  45. * it uses a binary heap to represent its task queue, so the cost to schedule
  46. * a task is O(log n), where n is the number of concurrently scheduled tasks.
  47. *
  48. * <p>Implementation note: All constructors start a timer thread.
  49. *
  50. * @author Josh Bloch
  51. * @version 1.17, 04/12/04
  52. * @see TimerTask
  53. * @see Object#wait(long)
  54. * @since 1.3
  55. */
  56. public class Timer {
  57. /**
  58. * The timer task queue. This data structure is shared with the timer
  59. * thread. The timer produces tasks, via its various schedule calls,
  60. * and the timer thread consumes, executing timer tasks as appropriate,
  61. * and removing them from the queue when they're obsolete.
  62. */
  63. private TaskQueue queue = new TaskQueue();
  64. /**
  65. * The timer thread.
  66. */
  67. private TimerThread thread = new TimerThread(queue);
  68. /**
  69. * This object causes the timer's task execution thread to exit
  70. * gracefully when there are no live references to the Timer object and no
  71. * tasks in the timer queue. It is used in preference to a finalizer on
  72. * Timer as such a finalizer would be susceptible to a subclass's
  73. * finalizer forgetting to call it.
  74. */
  75. private Object threadReaper = new Object() {
  76. protected void finalize() throws Throwable {
  77. synchronized(queue) {
  78. thread.newTasksMayBeScheduled = false;
  79. queue.notify(); // In case queue is empty.
  80. }
  81. }
  82. };
  83. /**
  84. * This ID is used to generate thread names. (It could be replaced
  85. * by an AtomicInteger as soon as they become available.)
  86. */
  87. private static int nextSerialNumber = 0;
  88. private static synchronized int serialNumber() {
  89. return nextSerialNumber++;
  90. }
  91. /**
  92. * Creates a new timer. The associated thread does <i>not</i> run as
  93. * a daemon.
  94. *
  95. * @see Thread
  96. * @see #cancel()
  97. */
  98. public Timer() {
  99. this("Timer-" + serialNumber());
  100. }
  101. /**
  102. * Creates a new timer whose associated thread may be specified to
  103. * run as a daemon. A daemon thread is called for if the timer will
  104. * be used to schedule repeating "maintenance activities", which must
  105. * be performed as long as the application is running, but should not
  106. * prolong the lifetime of the application.
  107. *
  108. * @param isDaemon true if the associated thread should run as a daemon.
  109. *
  110. * @see Thread
  111. * @see #cancel()
  112. */
  113. public Timer(boolean isDaemon) {
  114. this("Timer-" + serialNumber(), isDaemon);
  115. }
  116. /**
  117. * Creates a new timer whose associated thread has the specified name.
  118. * The associated thread does <i>not</i> run as a daemon.
  119. *
  120. * @param name the name of the associated thread
  121. * @throws NullPointerException if name is null
  122. * @see Thread#getName()
  123. * @see Thread#isDaemon()
  124. * @since 1.5
  125. */
  126. public Timer(String name) {
  127. thread.setName(name);
  128. thread.start();
  129. }
  130. /**
  131. * Creates a new timer whose associated thread has the specified name,
  132. * and may be specified to run as a daemon.
  133. *
  134. * @param name the name of the associated thread
  135. * @param isDaemon true if the associated thread should run as a daemon
  136. * @throws NullPointerException if name is null
  137. * @see Thread#getName()
  138. * @see Thread#isDaemon()
  139. * @since 1.5
  140. */
  141. public Timer(String name, boolean isDaemon) {
  142. thread.setName(name);
  143. thread.setDaemon(isDaemon);
  144. thread.start();
  145. }
  146. /**
  147. * Schedules the specified task for execution after the specified delay.
  148. *
  149. * @param task task to be scheduled.
  150. * @param delay delay in milliseconds before task is to be executed.
  151. * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
  152. * <tt>delay + System.currentTimeMillis()</tt> is negative.
  153. * @throws IllegalStateException if task was already scheduled or
  154. * cancelled, or timer was cancelled.
  155. */
  156. public void schedule(TimerTask task, long delay) {
  157. if (delay < 0)
  158. throw new IllegalArgumentException("Negative delay.");
  159. sched(task, System.currentTimeMillis()+delay, 0);
  160. }
  161. /**
  162. * Schedules the specified task for execution at the specified time. If
  163. * the time is in the past, the task is scheduled for immediate execution.
  164. *
  165. * @param task task to be scheduled.
  166. * @param time time at which task is to be executed.
  167. * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
  168. * @throws IllegalStateException if task was already scheduled or
  169. * cancelled, timer was cancelled, or timer thread terminated.
  170. */
  171. public void schedule(TimerTask task, Date time) {
  172. sched(task, time.getTime(), 0);
  173. }
  174. /**
  175. * Schedules the specified task for repeated <i>fixed-delay execution</i>,
  176. * beginning after the specified delay. Subsequent executions take place
  177. * at approximately regular intervals separated by the specified period.
  178. *
  179. * <p>In fixed-delay execution, each execution is scheduled relative to
  180. * the actual execution time of the previous execution. If an execution
  181. * is delayed for any reason (such as garbage collection or other
  182. * background activity), subsequent executions will be delayed as well.
  183. * In the long run, the frequency of execution will generally be slightly
  184. * lower than the reciprocal of the specified period (assuming the system
  185. * clock underlying <tt>Object.wait(long)</tt> is accurate).
  186. *
  187. * <p>Fixed-delay execution is appropriate for recurring activities
  188. * that require "smoothness." In other words, it is appropriate for
  189. * activities where it is more important to keep the frequency accurate
  190. * in the short run than in the long run. This includes most animation
  191. * tasks, such as blinking a cursor at regular intervals. It also includes
  192. * tasks wherein regular activity is performed in response to human
  193. * input, such as automatically repeating a character as long as a key
  194. * is held down.
  195. *
  196. * @param task task to be scheduled.
  197. * @param delay delay in milliseconds before task is to be executed.
  198. * @param period time in milliseconds between successive task executions.
  199. * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
  200. * <tt>delay + System.currentTimeMillis()</tt> is negative.
  201. * @throws IllegalStateException if task was already scheduled or
  202. * cancelled, timer was cancelled, or timer thread terminated.
  203. */
  204. public void schedule(TimerTask task, long delay, long period) {
  205. if (delay < 0)
  206. throw new IllegalArgumentException("Negative delay.");
  207. if (period <= 0)
  208. throw new IllegalArgumentException("Non-positive period.");
  209. sched(task, System.currentTimeMillis()+delay, -period);
  210. }
  211. /**
  212. * Schedules the specified task for repeated <i>fixed-delay execution</i>,
  213. * beginning at the specified time. Subsequent executions take place at
  214. * approximately regular intervals, separated by the specified period.
  215. *
  216. * <p>In fixed-delay execution, each execution is scheduled relative to
  217. * the actual execution time of the previous execution. If an execution
  218. * is delayed for any reason (such as garbage collection or other
  219. * background activity), subsequent executions will be delayed as well.
  220. * In the long run, the frequency of execution will generally be slightly
  221. * lower than the reciprocal of the specified period (assuming the system
  222. * clock underlying <tt>Object.wait(long)</tt> is accurate).
  223. *
  224. * <p>Fixed-delay execution is appropriate for recurring activities
  225. * that require "smoothness." In other words, it is appropriate for
  226. * activities where it is more important to keep the frequency accurate
  227. * in the short run than in the long run. This includes most animation
  228. * tasks, such as blinking a cursor at regular intervals. It also includes
  229. * tasks wherein regular activity is performed in response to human
  230. * input, such as automatically repeating a character as long as a key
  231. * is held down.
  232. *
  233. * @param task task to be scheduled.
  234. * @param firstTime First time at which task is to be executed.
  235. * @param period time in milliseconds between successive task executions.
  236. * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
  237. * @throws IllegalStateException if task was already scheduled or
  238. * cancelled, timer was cancelled, or timer thread terminated.
  239. */
  240. public void schedule(TimerTask task, Date firstTime, long period) {
  241. if (period <= 0)
  242. throw new IllegalArgumentException("Non-positive period.");
  243. sched(task, firstTime.getTime(), -period);
  244. }
  245. /**
  246. * Schedules the specified task for repeated <i>fixed-rate execution</i>,
  247. * beginning after the specified delay. Subsequent executions take place
  248. * at approximately regular intervals, separated by the specified period.
  249. *
  250. * <p>In fixed-rate execution, each execution is scheduled relative to the
  251. * scheduled execution time of the initial execution. If an execution is
  252. * delayed for any reason (such as garbage collection or other background
  253. * activity), two or more executions will occur in rapid succession to
  254. * "catch up." In the long run, the frequency of execution will be
  255. * exactly the reciprocal of the specified period (assuming the system
  256. * clock underlying <tt>Object.wait(long)</tt> is accurate).
  257. *
  258. * <p>Fixed-rate execution is appropriate for recurring activities that
  259. * are sensitive to <i>absolute</i> time, such as ringing a chime every
  260. * hour on the hour, or running scheduled maintenance every day at a
  261. * particular time. It is also appropriate for recurring activities
  262. * where the total time to perform a fixed number of executions is
  263. * important, such as a countdown timer that ticks once every second for
  264. * ten seconds. Finally, fixed-rate execution is appropriate for
  265. * scheduling multiple repeating timer tasks that must remain synchronized
  266. * with respect to one another.
  267. *
  268. * @param task task to be scheduled.
  269. * @param delay delay in milliseconds before task is to be executed.
  270. * @param period time in milliseconds between successive task executions.
  271. * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
  272. * <tt>delay + System.currentTimeMillis()</tt> is negative.
  273. * @throws IllegalStateException if task was already scheduled or
  274. * cancelled, timer was cancelled, or timer thread terminated.
  275. */
  276. public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
  277. if (delay < 0)
  278. throw new IllegalArgumentException("Negative delay.");
  279. if (period <= 0)
  280. throw new IllegalArgumentException("Non-positive period.");
  281. sched(task, System.currentTimeMillis()+delay, period);
  282. }
  283. /**
  284. * Schedules the specified task for repeated <i>fixed-rate execution</i>,
  285. * beginning at the specified time. Subsequent executions take place at
  286. * approximately regular intervals, separated by the specified period.
  287. *
  288. * <p>In fixed-rate execution, each execution is scheduled relative to the
  289. * scheduled execution time of the initial execution. If an execution is
  290. * delayed for any reason (such as garbage collection or other background
  291. * activity), two or more executions will occur in rapid succession to
  292. * "catch up." In the long run, the frequency of execution will be
  293. * exactly the reciprocal of the specified period (assuming the system
  294. * clock underlying <tt>Object.wait(long)</tt> is accurate).
  295. *
  296. * <p>Fixed-rate execution is appropriate for recurring activities that
  297. * are sensitive to <i>absolute</i> time, such as ringing a chime every
  298. * hour on the hour, or running scheduled maintenance every day at a
  299. * particular time. It is also appropriate for recurring activities
  300. * where the total time to perform a fixed number of executions is
  301. * important, such as a countdown timer that ticks once every second for
  302. * ten seconds. Finally, fixed-rate execution is appropriate for
  303. * scheduling multiple repeating timer tasks that must remain synchronized
  304. * with respect to one another.
  305. *
  306. * @param task task to be scheduled.
  307. * @param firstTime First time at which task is to be executed.
  308. * @param period time in milliseconds between successive task executions.
  309. * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
  310. * @throws IllegalStateException if task was already scheduled or
  311. * cancelled, timer was cancelled, or timer thread terminated.
  312. */
  313. public void scheduleAtFixedRate(TimerTask task, Date firstTime,
  314. long period) {
  315. if (period <= 0)
  316. throw new IllegalArgumentException("Non-positive period.");
  317. sched(task, firstTime.getTime(), period);
  318. }
  319. /**
  320. * Schedule the specified timer task for execution at the specified
  321. * time with the specified period, in milliseconds. If period is
  322. * positive, the task is scheduled for repeated execution; if period is
  323. * zero, the task is scheduled for one-time execution. Time is specified
  324. * in Date.getTime() format. This method checks timer state, task state,
  325. * and initial execution time, but not period.
  326. *
  327. * @throws IllegalArgumentException if <tt>time()</tt> is negative.
  328. * @throws IllegalStateException if task was already scheduled or
  329. * cancelled, timer was cancelled, or timer thread terminated.
  330. */
  331. private void sched(TimerTask task, long time, long period) {
  332. if (time < 0)
  333. throw new IllegalArgumentException("Illegal execution time.");
  334. synchronized(queue) {
  335. if (!thread.newTasksMayBeScheduled)
  336. throw new IllegalStateException("Timer already cancelled.");
  337. synchronized(task.lock) {
  338. if (task.state != TimerTask.VIRGIN)
  339. throw new IllegalStateException(
  340. "Task already scheduled or cancelled");
  341. task.nextExecutionTime = time;
  342. task.period = period;
  343. task.state = TimerTask.SCHEDULED;
  344. }
  345. queue.add(task);
  346. if (queue.getMin() == task)
  347. queue.notify();
  348. }
  349. }
  350. /**
  351. * Terminates this timer, discarding any currently scheduled tasks.
  352. * Does not interfere with a currently executing task (if it exists).
  353. * Once a timer has been terminated, its execution thread terminates
  354. * gracefully, and no more tasks may be scheduled on it.
  355. *
  356. * <p>Note that calling this method from within the run method of a
  357. * timer task that was invoked by this timer absolutely guarantees that
  358. * the ongoing task execution is the last task execution that will ever
  359. * be performed by this timer.
  360. *
  361. * <p>This method may be called repeatedly; the second and subsequent
  362. * calls have no effect.
  363. */
  364. public void cancel() {
  365. synchronized(queue) {
  366. thread.newTasksMayBeScheduled = false;
  367. queue.clear();
  368. queue.notify(); // In case queue was already empty.
  369. }
  370. }
  371. /**
  372. * Removes all cancelled tasks from this timer's task queue. <i>Calling
  373. * this method has no effect on the behavior of the timer</i>, but
  374. * eliminates the references to the cancelled tasks from the queue.
  375. * If there are no external references to these tasks, they become
  376. * eligible for garbage collection.
  377. *
  378. * <p>Most programs will have no need to call this method.
  379. * It is designed for use by the rare application that cancels a large
  380. * number of tasks. Calling this method trades time for space: the
  381. * runtime of the method may be proportional to n + c log n, where n
  382. * is the number of tasks in the queue and c is the number of cancelled
  383. * tasks.
  384. *
  385. * <p>Note that it is permissible to call this method from within a
  386. * a task scheduled on this timer.
  387. *
  388. * @return the number of tasks removed from the queue.
  389. * @since 1.5
  390. */
  391. public int purge() {
  392. int result = 0;
  393. synchronized(queue) {
  394. for (int i = queue.size(); i > 0; i--) {
  395. if (queue.get(i).state == TimerTask.CANCELLED) {
  396. queue.quickRemove(i);
  397. result++;
  398. }
  399. }
  400. if (result != 0)
  401. queue.heapify();
  402. }
  403. return result;
  404. }
  405. }
  406. /**
  407. * This "helper class" implements the timer's task execution thread, which
  408. * waits for tasks on the timer queue, executions them when they fire,
  409. * reschedules repeating tasks, and removes cancelled tasks and spent
  410. * non-repeating tasks from the queue.
  411. */
  412. class TimerThread extends Thread {
  413. /**
  414. * This flag is set to false by the reaper to inform us that there
  415. * are no more live references to our Timer object. Once this flag
  416. * is true and there are no more tasks in our queue, there is no
  417. * work left for us to do, so we terminate gracefully. Note that
  418. * this field is protected by queue's monitor!
  419. */
  420. boolean newTasksMayBeScheduled = true;
  421. /**
  422. * Our Timer's queue. We store this reference in preference to
  423. * a reference to the Timer so the reference graph remains acyclic.
  424. * Otherwise, the Timer would never be garbage-collected and this
  425. * thread would never go away.
  426. */
  427. private TaskQueue queue;
  428. TimerThread(TaskQueue queue) {
  429. this.queue = queue;
  430. }
  431. public void run() {
  432. try {
  433. mainLoop();
  434. } finally {
  435. // Someone killed this Thread, behave as if Timer cancelled
  436. synchronized(queue) {
  437. newTasksMayBeScheduled = false;
  438. queue.clear(); // Eliminate obsolete references
  439. }
  440. }
  441. }
  442. /**
  443. * The main timer loop. (See class comment.)
  444. */
  445. private void mainLoop() {
  446. while (true) {
  447. try {
  448. TimerTask task;
  449. boolean taskFired;
  450. synchronized(queue) {
  451. // Wait for queue to become non-empty
  452. while (queue.isEmpty() && newTasksMayBeScheduled)
  453. queue.wait();
  454. if (queue.isEmpty())
  455. break; // Queue is empty and will forever remain; die
  456. // Queue nonempty; look at first evt and do the right thing
  457. long currentTime, executionTime;
  458. task = queue.getMin();
  459. synchronized(task.lock) {
  460. if (task.state == TimerTask.CANCELLED) {
  461. queue.removeMin();
  462. continue; // No action required, poll queue again
  463. }
  464. currentTime = System.currentTimeMillis();
  465. executionTime = task.nextExecutionTime;
  466. if (taskFired = (executionTime<=currentTime)) {
  467. if (task.period == 0) { // Non-repeating, remove
  468. queue.removeMin();
  469. task.state = TimerTask.EXECUTED;
  470. } else { // Repeating task, reschedule
  471. queue.rescheduleMin(
  472. task.period<0 ? currentTime - task.period
  473. : executionTime + task.period);
  474. }
  475. }
  476. }
  477. if (!taskFired) // Task hasn't yet fired; wait
  478. queue.wait(executionTime - currentTime);
  479. }
  480. if (taskFired) // Task fired; run it, holding no locks
  481. task.run();
  482. } catch(InterruptedException e) {
  483. }
  484. }
  485. }
  486. }
  487. /**
  488. * This class represents a timer task queue: a priority queue of TimerTasks,
  489. * ordered on nextExecutionTime. Each Timer object has one of these, which it
  490. * shares with its TimerThread. Internally this class uses a heap, which
  491. * offers log(n) performance for the add, removeMin and rescheduleMin
  492. * operations, and constant time performance for the getMin operation.
  493. */
  494. class TaskQueue {
  495. /**
  496. * Priority queue represented as a balanced binary heap: the two children
  497. * of queue[n] are queue[2*n] and queue[2*n+1]. The priority queue is
  498. * ordered on the nextExecutionTime field: The TimerTask with the lowest
  499. * nextExecutionTime is in queue[1] (assuming the queue is nonempty). For
  500. * each node n in the heap, and each descendant of n, d,
  501. * n.nextExecutionTime <= d.nextExecutionTime.
  502. */
  503. private TimerTask[] queue = new TimerTask[128];
  504. /**
  505. * The number of tasks in the priority queue. (The tasks are stored in
  506. * queue[1] up to queue[size]).
  507. */
  508. private int size = 0;
  509. /**
  510. * Returns the number of tasks currently on the queue.
  511. */
  512. int size() {
  513. return size;
  514. }
  515. /**
  516. * Adds a new task to the priority queue.
  517. */
  518. void add(TimerTask task) {
  519. // Grow backing store if necessary
  520. if (++size == queue.length) {
  521. TimerTask[] newQueue = new TimerTask[2*queue.length];
  522. System.arraycopy(queue, 0, newQueue, 0, size);
  523. queue = newQueue;
  524. }
  525. queue[size] = task;
  526. fixUp(size);
  527. }
  528. /**
  529. * Return the "head task" of the priority queue. (The head task is an
  530. * task with the lowest nextExecutionTime.)
  531. */
  532. TimerTask getMin() {
  533. return queue[1];
  534. }
  535. /**
  536. * Return the ith task in the priority queue, where i ranges from 1 (the
  537. * head task, which is returned by getMin) to the number of tasks on the
  538. * queue, inclusive.
  539. */
  540. TimerTask get(int i) {
  541. return queue[i];
  542. }
  543. /**
  544. * Remove the head task from the priority queue.
  545. */
  546. void removeMin() {
  547. queue[1] = queue[size];
  548. queue[size--] = null; // Drop extra reference to prevent memory leak
  549. fixDown(1);
  550. }
  551. /**
  552. * Removes the ith element from queue without regard for maintaining
  553. * the heap invariant. Recall that queue is one-based, so
  554. * 1 <= i <= size.
  555. */
  556. void quickRemove(int i) {
  557. assert i <= size;
  558. queue[i] = queue[size];
  559. queue[size--] = null; // Drop extra ref to prevent memory leak
  560. }
  561. /**
  562. * Sets the nextExecutionTime associated with the head task to the
  563. * specified value, and adjusts priority queue accordingly.
  564. */
  565. void rescheduleMin(long newTime) {
  566. queue[1].nextExecutionTime = newTime;
  567. fixDown(1);
  568. }
  569. /**
  570. * Returns true if the priority queue contains no elements.
  571. */
  572. boolean isEmpty() {
  573. return size==0;
  574. }
  575. /**
  576. * Removes all elements from the priority queue.
  577. */
  578. void clear() {
  579. // Null out task references to prevent memory leak
  580. for (int i=1; i<=size; i++)
  581. queue[i] = null;
  582. size = 0;
  583. }
  584. /**
  585. * Establishes the heap invariant (described above) assuming the heap
  586. * satisfies the invariant except possibly for the leaf-node indexed by k
  587. * (which may have a nextExecutionTime less than its parent's).
  588. *
  589. * This method functions by "promoting" queue[k] up the hierarchy
  590. * (by swapping it with its parent) repeatedly until queue[k]'s
  591. * nextExecutionTime is greater than or equal to that of its parent.
  592. */
  593. private void fixUp(int k) {
  594. while (k > 1) {
  595. int j = k >> 1;
  596. if (queue[j].nextExecutionTime <= queue[k].nextExecutionTime)
  597. break;
  598. TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
  599. k = j;
  600. }
  601. }
  602. /**
  603. * Establishes the heap invariant (described above) in the subtree
  604. * rooted at k, which is assumed to satisfy the heap invariant except
  605. * possibly for node k itself (which may have a nextExecutionTime greater
  606. * than its children's).
  607. *
  608. * This method functions by "demoting" queue[k] down the hierarchy
  609. * (by swapping it with its smaller child) repeatedly until queue[k]'s
  610. * nextExecutionTime is less than or equal to those of its children.
  611. */
  612. private void fixDown(int k) {
  613. int j;
  614. while ((j = k << 1) <= size && j > 0) {
  615. if (j < size &&
  616. queue[j].nextExecutionTime > queue[j+1].nextExecutionTime)
  617. j++; // j indexes smallest kid
  618. if (queue[k].nextExecutionTime <= queue[j].nextExecutionTime)
  619. break;
  620. TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
  621. k = j;
  622. }
  623. }
  624. /**
  625. * Establishes the heap invariant (described above) in the entire tree,
  626. * assuming nothing about the order of the elements prior to the call.
  627. */
  628. void heapify() {
  629. for (int i = size2; i >= 1; i--)
  630. fixDown(i);
  631. }
  632. }