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