1. /*
  2. * @(#)Timer.java 1.9 03/01/23
  3. *
  4. * Copyright 2003 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 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. * @author Josh Bloch
  49. * @version 1.9, 01/23/03
  50. * @see TimerTask
  51. * @see Object#wait(long)
  52. * @since 1.3
  53. */
  54. public class Timer {
  55. /**
  56. * The timer task queue. This data structure is shared with the timer
  57. * thread. The timer produces tasks, via its various schedule calls,
  58. * and the timer thread consumes, executing timer tasks as appropriate,
  59. * and removing them from the queue when they're obsolete.
  60. */
  61. private TaskQueue queue = new TaskQueue();
  62. /**
  63. * The timer thread.
  64. */
  65. private TimerThread thread = new TimerThread(queue);
  66. /**
  67. * This object causes the timer's task execution thread to exit
  68. * gracefully when there are no live references to the Timer object and no
  69. * tasks in the timer queue. It is used in preference to a finalizer on
  70. * Timer as such a finalizer would be susceptible to a subclass's
  71. * finalizer forgetting to call it.
  72. */
  73. private Object threadReaper = new Object() {
  74. protected void finalize() throws Throwable {
  75. synchronized(queue) {
  76. thread.newTasksMayBeScheduled = false;
  77. queue.notify(); // In case queue is empty.
  78. }
  79. }
  80. };
  81. /**
  82. * Creates a new timer. The associated thread does <i>not</i> run as
  83. * a daemon.
  84. *
  85. * @see Thread
  86. * @see #cancel()
  87. */
  88. public Timer() {
  89. thread.start();
  90. }
  91. /**
  92. * Creates a new timer whose associated thread may be specified to
  93. * run as a daemon. A deamon thread is called for if the timer will
  94. * be used to schedule repeating "maintenance activities", which must
  95. * be performed as long as the application is running, but should not
  96. * prolong the lifetime of the application.
  97. *
  98. * @param isDaemon true if the associated thread should run as a daemon.
  99. *
  100. * @see Thread
  101. * @see #cancel()
  102. */
  103. public Timer(boolean isDaemon) {
  104. thread.setDaemon(isDaemon);
  105. thread.start();
  106. }
  107. /**
  108. * Schedules the specified task for execution after the specified delay.
  109. *
  110. * @param task task to be scheduled.
  111. * @param delay delay in milliseconds before task is to be executed.
  112. * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
  113. * <tt>delay + System.currentTimeMillis()</tt> is negative.
  114. * @throws IllegalStateException if task was already scheduled or
  115. * cancelled, or timer was cancelled.
  116. */
  117. public void schedule(TimerTask task, long delay) {
  118. if (delay < 0)
  119. throw new IllegalArgumentException("Negative delay.");
  120. sched(task, System.currentTimeMillis()+delay, 0);
  121. }
  122. /**
  123. * Schedules the specified task for execution at the specified time. If
  124. * the time is in the past, the task is scheduled for immediate execution.
  125. *
  126. * @param task task to be scheduled.
  127. * @param time time at which task is to be executed.
  128. * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
  129. * @throws IllegalStateException if task was already scheduled or
  130. * cancelled, timer was cancelled, or timer thread terminated.
  131. */
  132. public void schedule(TimerTask task, Date time) {
  133. sched(task, time.getTime(), 0);
  134. }
  135. /**
  136. * Schedules the specified task for repeated <i>fixed-delay execution</i>,
  137. * beginning after the specified delay. Subsequent executions take place
  138. * at approximately regular intervals separated by the specified period.
  139. *
  140. * <p>In fixed-delay execution, each execution is scheduled relative to
  141. * the actual execution time of the previous execution. If an execution
  142. * is delayed for any reason (such as garbage collection or other
  143. * background activity), subsequent executions will be delayed as well.
  144. * In the long run, the frequency of execution will generally be slightly
  145. * lower than the reciprocal of the specified period (assuming the system
  146. * clock underlying <tt>Object.wait(long)</tt> is accurate).
  147. *
  148. * <p>Fixed-delay execution is appropriate for recurring activities
  149. * that require "smoothness." In other words, it is appropriate for
  150. * activities where it is more important to keep the frequency accurate
  151. * in the short run than in the long run. This includes most animation
  152. * tasks, such as blinking a cursor at regular intervals. It also includes
  153. * tasks wherein regular activity is performed in response to human
  154. * input, such as automatically repeating a character as long as a key
  155. * is held down.
  156. *
  157. * @param task task to be scheduled.
  158. * @param delay delay in milliseconds before task is to be executed.
  159. * @param period time in milliseconds between successive task executions.
  160. * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
  161. * <tt>delay + System.currentTimeMillis()</tt> is negative.
  162. * @throws IllegalStateException if task was already scheduled or
  163. * cancelled, timer was cancelled, or timer thread terminated.
  164. */
  165. public void schedule(TimerTask task, long delay, long period) {
  166. if (delay < 0)
  167. throw new IllegalArgumentException("Negative delay.");
  168. if (period <= 0)
  169. throw new IllegalArgumentException("Non-positive period.");
  170. sched(task, System.currentTimeMillis()+delay, -period);
  171. }
  172. /**
  173. * Schedules the specified task for repeated <i>fixed-delay execution</i>,
  174. * beginning at the specified time. Subsequent executions take place at
  175. * approximately regular intervals, separated by the specified period.
  176. *
  177. * <p>In fixed-delay execution, each execution is scheduled relative to
  178. * the actual execution time of the previous execution. If an execution
  179. * is delayed for any reason (such as garbage collection or other
  180. * background activity), subsequent executions will be delayed as well.
  181. * In the long run, the frequency of execution will generally be slightly
  182. * lower than the reciprocal of the specified period (assuming the system
  183. * clock underlying <tt>Object.wait(long)</tt> is accurate).
  184. *
  185. * <p>Fixed-delay execution is appropriate for recurring activities
  186. * that require "smoothness." In other words, it is appropriate for
  187. * activities where it is more important to keep the frequency accurate
  188. * in the short run than in the long run. This includes most animation
  189. * tasks, such as blinking a cursor at regular intervals. It also includes
  190. * tasks wherein regular activity is performed in response to human
  191. * input, such as automatically repeating a character as long as a key
  192. * is held down.
  193. *
  194. * @param task task to be scheduled.
  195. * @param firstTime First time at which task is to be executed.
  196. * @param period time in milliseconds between successive task executions.
  197. * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
  198. * @throws IllegalStateException if task was already scheduled or
  199. * cancelled, timer was cancelled, or timer thread terminated.
  200. */
  201. public void schedule(TimerTask task, Date firstTime, long period) {
  202. if (period <= 0)
  203. throw new IllegalArgumentException("Non-positive period.");
  204. sched(task, firstTime.getTime(), -period);
  205. }
  206. /**
  207. * Schedules the specified task for repeated <i>fixed-rate execution</i>,
  208. * beginning after the specified delay. Subsequent executions take place
  209. * at approximately regular intervals, separated by the specified period.
  210. *
  211. * <p>In fixed-rate execution, each execution is scheduled relative to the
  212. * scheduled execution time of the initial execution. If an execution is
  213. * delayed for any reason (such as garbage collection or other background
  214. * activity), two or more executions will occur in rapid succession to
  215. * "catch up." In the long run, the frequency of execution will be
  216. * exactly the reciprocal of the specified period (assuming the system
  217. * clock underlying <tt>Object.wait(long)</tt> is accurate).
  218. *
  219. * <p>Fixed-rate execution is appropriate for recurring activities that
  220. * are sensitive to <i>absolute</i> time, such as ringing a chime every
  221. * hour on the hour, or running scheduled maintenance every day at a
  222. * particular time. It is also appropriate for for recurring activities
  223. * where the total time to perform a fixed number of executions is
  224. * important, such as a countdown timer that ticks once every second for
  225. * ten seconds. Finally, fixed-rate execution is appropriate for
  226. * scheduling multiple repeating timer tasks that must remain synchronized
  227. * with respect to one another.
  228. *
  229. * @param task task to be scheduled.
  230. * @param delay delay in milliseconds before task is to be executed.
  231. * @param period time in milliseconds between successive task executions.
  232. * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
  233. * <tt>delay + System.currentTimeMillis()</tt> is negative.
  234. * @throws IllegalStateException if task was already scheduled or
  235. * cancelled, timer was cancelled, or timer thread terminated.
  236. */
  237. public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
  238. if (delay < 0)
  239. throw new IllegalArgumentException("Negative delay.");
  240. if (period <= 0)
  241. throw new IllegalArgumentException("Non-positive period.");
  242. sched(task, System.currentTimeMillis()+delay, period);
  243. }
  244. /**
  245. * Schedules the specified task for repeated <i>fixed-rate execution</i>,
  246. * beginning at the specified time. Subsequent executions take place at
  247. * approximately regular intervals, separated by the specified period.
  248. *
  249. * <p>In fixed-rate execution, each execution is scheduled relative to the
  250. * scheduled execution time of the initial execution. If an execution is
  251. * delayed for any reason (such as garbage collection or other background
  252. * activity), two or more executions will occur in rapid succession to
  253. * "catch up." In the long run, the frequency of execution will be
  254. * exactly the reciprocal of the specified period (assuming the system
  255. * clock underlying <tt>Object.wait(long)</tt> is accurate).
  256. *
  257. * <p>Fixed-rate execution is appropriate for recurring activities that
  258. * are sensitive to <i>absolute</i> time, such as ringing a chime every
  259. * hour on the hour, or running scheduled maintenance every day at a
  260. * particular time. It is also appropriate for for recurring activities
  261. * where the total time to perform a fixed number of executions is
  262. * important, such as a countdown timer that ticks once every second for
  263. * ten seconds. Finally, fixed-rate execution is appropriate for
  264. * scheduling multiple repeating timer tasks that must remain synchronized
  265. * with respect to one another.
  266. *
  267. * @param task task to be scheduled.
  268. * @param firstTime First time at which task is to be executed.
  269. * @param period time in milliseconds between successive task executions.
  270. * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
  271. * @throws IllegalStateException if task was already scheduled or
  272. * cancelled, timer was cancelled, or timer thread terminated.
  273. */
  274. public void scheduleAtFixedRate(TimerTask task, Date firstTime,
  275. long period) {
  276. if (period <= 0)
  277. throw new IllegalArgumentException("Non-positive period.");
  278. sched(task, firstTime.getTime(), period);
  279. }
  280. /**
  281. * Schedule the specifed timer task for execution at the specified
  282. * time with the specified period, in milliseconds. If period is
  283. * positive, the task is scheduled for repeated execution; if period is
  284. * zero, the task is scheduled for one-time execution. Time is specified
  285. * in Date.getTime() format. This method checks timer state, task state,
  286. * and initial execution time, but not period.
  287. *
  288. * @throws IllegalArgumentException if <tt>time()</tt> is negative.
  289. * @throws IllegalStateException if task was already scheduled or
  290. * cancelled, timer was cancelled, or timer thread terminated.
  291. */
  292. private void sched(TimerTask task, long time, long period) {
  293. if (time < 0)
  294. throw new IllegalArgumentException("Illegal execution time.");
  295. synchronized(queue) {
  296. if (!thread.newTasksMayBeScheduled)
  297. throw new IllegalStateException("Timer already cancelled.");
  298. synchronized(task.lock) {
  299. if (task.state != TimerTask.VIRGIN)
  300. throw new IllegalStateException(
  301. "Task already scheduled or cancelled");
  302. task.nextExecutionTime = time;
  303. task.period = period;
  304. task.state = TimerTask.SCHEDULED;
  305. }
  306. queue.add(task);
  307. if (queue.getMin() == task)
  308. queue.notify();
  309. }
  310. }
  311. /**
  312. * Terminates this timer, discarding any currently scheduled tasks.
  313. * Does not interfere with a currently executing task (if it exists).
  314. * Once a timer has been terminated, its execution thread terminates
  315. * gracefully, and no more tasks may be scheduled on it.
  316. *
  317. * <p>Note that calling this method from within the run method of a
  318. * timer task that was invoked by this timer absolutely guarantees that
  319. * the ongoing task execution is the last task execution that will ever
  320. * be performed by this timer.
  321. *
  322. * <p>This method may be called repeatedly; the second and subsequent
  323. * calls have no effect.
  324. */
  325. public void cancel() {
  326. synchronized(queue) {
  327. thread.newTasksMayBeScheduled = false;
  328. queue.clear();
  329. queue.notify(); // In case queue was already empty.
  330. }
  331. }
  332. }
  333. /**
  334. * This "helper class" implements the timer's task execution thread, which
  335. * waits for tasks on the timer queue, executions them when they fire,
  336. * reschedules repeating tasks, and removes cancelled tasks and spent
  337. * non-repeating tasks from the queue.
  338. */
  339. class TimerThread extends Thread {
  340. /**
  341. * This flag is set to false by the reaper to inform us that there
  342. * are no more live references to our Timer object. Once this flag
  343. * is true and there are no more tasks in our queue, there is no
  344. * work left for us to do, so we terminate gracefully. Note that
  345. * this field is protected by queue's monitor!
  346. */
  347. boolean newTasksMayBeScheduled = true;
  348. /**
  349. * Our Timer's queue. We store this reference in preference to
  350. * a reference to the Timer so the reference graph remains acyclic.
  351. * Otherwise, the Timer would never be garbage-collected and this
  352. * thread would never go away.
  353. */
  354. private TaskQueue queue;
  355. TimerThread(TaskQueue queue) {
  356. this.queue = queue;
  357. }
  358. public void run() {
  359. try {
  360. mainLoop();
  361. } finally {
  362. // Somone killed this Thread, behave as if Timer cancelled
  363. synchronized(queue) {
  364. newTasksMayBeScheduled = false;
  365. queue.clear(); // Eliminate obsolete references
  366. }
  367. }
  368. }
  369. /**
  370. * The main timer loop. (See class comment.)
  371. */
  372. private void mainLoop() {
  373. while (true) {
  374. try {
  375. TimerTask task;
  376. boolean taskFired;
  377. synchronized(queue) {
  378. // Wait for queue to become non-empty
  379. while (queue.isEmpty() && newTasksMayBeScheduled)
  380. queue.wait();
  381. if (queue.isEmpty())
  382. break; // Queue is empty and will forever remain; die
  383. // Queue nonempty; look at first evt and do the right thing
  384. long currentTime, executionTime;
  385. task = queue.getMin();
  386. synchronized(task.lock) {
  387. if (task.state == TimerTask.CANCELLED) {
  388. queue.removeMin();
  389. continue; // No action required, poll queue again
  390. }
  391. currentTime = System.currentTimeMillis();
  392. executionTime = task.nextExecutionTime;
  393. if (taskFired = (executionTime<=currentTime)) {
  394. if (task.period == 0) { // Non-repeating, remove
  395. queue.removeMin();
  396. task.state = TimerTask.EXECUTED;
  397. } else { // Repeating task, reschedule
  398. queue.rescheduleMin(
  399. task.period<0 ? currentTime - task.period
  400. : executionTime + task.period);
  401. }
  402. }
  403. }
  404. if (!taskFired) // Task hasn't yet fired; wait
  405. queue.wait(executionTime - currentTime);
  406. }
  407. if (taskFired) // Task fired; run it, holding no locks
  408. task.run();
  409. } catch(InterruptedException e) {
  410. }
  411. }
  412. }
  413. }
  414. /**
  415. * This class represents a timer task queue: a priority queue of TimerTasks,
  416. * ordered on nextExecutionTime. Each Timer object has one of these, which it
  417. * shares with its TimerThread. Internally this class uses a heap, which
  418. * offers log(n) performance for the add, removeMin and rescheduleMin
  419. * operations, and constant time performance for the the getMin operation.
  420. */
  421. class TaskQueue {
  422. /**
  423. * Priority queue represented as a balanced binary heap: the two children
  424. * of queue[n] are queue[2*n] and queue[2*n+1]. The priority queue is
  425. * ordered on the nextExecutionTime field: The TimerTask with the lowest
  426. * nextExecutionTime is in queue[1] (assuming the queue is nonempty). For
  427. * each node n in the heap, and each descendant of n, d,
  428. * n.nextExecutionTime <= d.nextExecutionTime.
  429. */
  430. private TimerTask[] queue = new TimerTask[128];
  431. /**
  432. * The number of tasks in the priority queue. (The tasks are stored in
  433. * queue[1] up to queue[size]).
  434. */
  435. private int size = 0;
  436. /**
  437. * Adds a new task to the priority queue.
  438. */
  439. void add(TimerTask task) {
  440. // Grow backing store if necessary
  441. if (++size == queue.length) {
  442. TimerTask[] newQueue = new TimerTask[2*queue.length];
  443. System.arraycopy(queue, 0, newQueue, 0, size);
  444. queue = newQueue;
  445. }
  446. queue[size] = task;
  447. fixUp(size);
  448. }
  449. /**
  450. * Return the "head task" of the priority queue. (The head task is an
  451. * task with the lowest nextExecutionTime.)
  452. */
  453. TimerTask getMin() {
  454. return queue[1];
  455. }
  456. /**
  457. * Remove the head task from the priority queue.
  458. */
  459. void removeMin() {
  460. queue[1] = queue[size];
  461. queue[size--] = null; // Drop extra reference to prevent memory leak
  462. fixDown(1);
  463. }
  464. /**
  465. * Sets the nextExecutionTime associated with the head task to the
  466. * specified value, and adjusts priority queue accordingly.
  467. */
  468. void rescheduleMin(long newTime) {
  469. queue[1].nextExecutionTime = newTime;
  470. fixDown(1);
  471. }
  472. /**
  473. * Returns true if the priority queue contains no elements.
  474. */
  475. boolean isEmpty() {
  476. return size==0;
  477. }
  478. /**
  479. * Removes all elements from the priority queue.
  480. */
  481. void clear() {
  482. // Null out task references to prevent memory leak
  483. for (int i=1; i<=size; i++)
  484. queue[i] = null;
  485. size = 0;
  486. }
  487. /**
  488. * Establishes the heap invariant (described above) assuming the heap
  489. * satisfies the invariant except possibly for the leaf-node indexed by k
  490. * (which may have a nextExecutionTime less than its parent's).
  491. *
  492. * This method functions by "promoting" queue[k] up the hierarchy
  493. * (by swapping it with its parent) repeatedly until queue[k]'s
  494. * nextExecutionTime is greater than or equal to that of its parent.
  495. */
  496. private void fixUp(int k) {
  497. while (k > 1) {
  498. int j = k >> 1;
  499. if (queue[j].nextExecutionTime <= queue[k].nextExecutionTime)
  500. break;
  501. TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
  502. k = j;
  503. }
  504. }
  505. /**
  506. * Establishes the heap invariant (described above) in the subtree
  507. * rooted at k, which is assumed to satisfy the heap invariant except
  508. * possibly for node k itself (which may have a nextExecutionTime greater
  509. * than its children's).
  510. *
  511. * This method functions by "demoting" queue[k] down the hierarchy
  512. * (by swapping it with its smaller child) repeatedly until queue[k]'s
  513. * nextExecutionTime is less than or equal to those of its children.
  514. */
  515. private void fixDown(int k) {
  516. int j;
  517. while ((j = k << 1) <= size) {
  518. if (j < size &&
  519. queue[j].nextExecutionTime > queue[j+1].nextExecutionTime)
  520. j++; // j indexes smallest kid
  521. if (queue[k].nextExecutionTime <= queue[j].nextExecutionTime)
  522. break;
  523. TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
  524. k = j;
  525. }
  526. }
  527. }