OSDN Git Service

a5e877640fb713b0f7c3e9c7d3607874308f08d8
[pf3gnuchains/gcc-fork.git] / libjava / java / util / Timer.java
1 /* Timer.java -- Timer that runs TimerTasks at a later time.
2    Copyright (C) 2000, 2001 Free Software Foundation, Inc.
3
4 This file is part of GNU Classpath.
5
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING.  If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA.
20
21 As a special exception, if you link this library with other files to
22 produce an executable, this library does not by itself cause the
23 resulting executable to be covered by the GNU General Public License.
24 This exception does not however invalidate any other reasons why the
25 executable file might be covered by the GNU General Public License. */
26
27 package java.util;
28
29 /**
30  * Timer that can run TimerTasks at a later time.
31  * TimerTasks can be scheduled for one time execution at some time in the
32  * future. They can be scheduled to be rescheduled at a time period after the
33  * task was last executed. Or they can be scheduled to be executed repeatedly
34  * at a fixed rate.
35  * <p>
36  * The normal scheduling will result in a more or less even delay in time
37  * between successive executions, but the executions could drift in time if
38  * the task (or other tasks) takes a long time to execute. Fixed delay
39  * scheduling guarantees more or less that the task will be executed at a
40  * specific time, but if there is ever a delay in execution then the period
41  * between successive executions will be shorter. The first method of
42  * repeated scheduling is preferred for repeated tasks in response to user
43  * interaction, the second method of repeated scheduling is preferred for tasks
44  * that act like alarms.
45  * <p>
46  * The Timer keeps a binary heap as a task priority queue which means that
47  * scheduling and serving of a task in a queue of n tasks costs O(log n).
48  *
49  * @see TimerTask
50  * @since 1.3
51  * @author Mark Wielaard (mark@klomp.org)
52  */
53 public class Timer
54 {
55   /**
56    * Priority Task Queue.
57    * TimerTasks are kept in a binary heap.
58    * The scheduler calls sleep() on the queue when it has nothing to do or
59    * has to wait. A sleeping scheduler can be notified by calling interrupt()
60    * which is automatically called by the enqueue(), cancel() and
61    * timerFinalized() methods.
62    */
63   private static final class TaskQueue
64   {
65     /** Default size of this queue */
66     private final int DEFAULT_SIZE = 32;
67
68     /** Whether to return null when there is nothing in the queue */
69     private boolean nullOnEmpty;
70
71     /**
72      * The heap containing all the scheduled TimerTasks
73      * sorted by the TimerTask.scheduled field.
74      * Null when the stop() method has been called.
75      */
76     private TimerTask heap[];
77
78     /**
79      * The actual number of elements in the heap
80      * Can be less then heap.length.
81      * Note that heap[0] is used as a sentinel.
82      */
83     private int elements;
84
85     /**
86      * Creates a TaskQueue of default size without any elements in it.
87      */
88     public TaskQueue()
89     {
90       heap = new TimerTask[DEFAULT_SIZE];
91       elements = 0;
92       nullOnEmpty = false;
93     }
94
95     /**
96      * Adds a TimerTask at the end of the heap.
97      * Grows the heap if necessary by doubling the heap in size.
98      */
99     private void add(TimerTask task)
100     {
101       elements++;
102       if (elements == heap.length)
103         {
104           TimerTask new_heap[] = new TimerTask[heap.length * 2];
105           System.arraycopy(heap, 0, new_heap, 0, heap.length);
106           heap = new_heap;
107         }
108       heap[elements] = task;
109     }
110
111     /**
112      * Removes the last element from the heap.
113      * Shrinks the heap in half if
114      * elements+DEFAULT_SIZE/2 <= heap.length/4.
115      */
116     private void remove()
117     {
118       // clear the entry first
119       heap[elements] = null;
120       elements--;
121       if (elements + DEFAULT_SIZE / 2 <= (heap.length / 4))
122         {
123           TimerTask new_heap[] = new TimerTask[heap.length / 2];
124           System.arraycopy(heap, 0, new_heap, 0, elements + 1);
125           heap = new_heap;
126         }
127     }
128
129     /**
130      * Adds a task to the queue and puts it at the correct place
131      * in the heap.
132      */
133     public synchronized void enqueue(TimerTask task)
134     {
135       // Check if it is legal to add another element
136       if (heap == null)
137         {
138           throw new IllegalStateException
139             ("cannot enqueue when stop() has been called on queue");
140         }
141
142       heap[0] = task;           // sentinel
143       add(task);                // put the new task at the end
144       // Now push the task up in the heap until it has reached its place
145       int child = elements;
146       int parent = child / 2;
147       while (heap[parent].scheduled > task.scheduled)
148         {
149           heap[child] = heap[parent];
150           child = parent;
151           parent = child / 2;
152         }
153       // This is the correct place for the new task
154       heap[child] = task;
155       heap[0] = null;           // clear sentinel
156       // Maybe sched() is waiting for a new element
157       this.notify();
158     }
159
160     /**
161      * Returns the top element of the queue.
162      * Can return null when no task is in the queue.
163      */
164     private TimerTask top()
165     {
166       if (elements == 0)
167         {
168           return null;
169         }
170       else
171         {
172           return heap[1];
173         }
174     }
175
176     /**
177      * Returns the top task in the Queue.
178      * Removes the element from the heap and reorders the heap first.
179      * Can return null when there is nothing in the queue.
180      */
181     public synchronized TimerTask serve()
182     {
183       // The task to return
184       TimerTask task = null;
185
186       while (task == null)
187         {
188           // Get the next task
189           task = top();
190
191           // return null when asked to stop
192           // or if asked to return null when the queue is empty
193           if ((heap == null) || (task == null && nullOnEmpty))
194             {
195               return null;
196             }
197
198           // Do we have a task?
199           if (task != null)
200             {
201               // The time to wait until the task should be served
202               long time = task.scheduled - System.currentTimeMillis();
203               if (time > 0)
204                 {
205                   // This task should not yet be served
206                   // So wait until this task is ready
207                   // or something else happens to the queue
208                   task = null;  // set to null to make sure we call top()
209                   try
210                     {
211                       this.wait(time);
212                     }
213                   catch (InterruptedException _)
214                     {
215                     }
216                 }
217             }
218           else
219             {
220               // wait until a task is added
221               // or something else happens to the queue
222               try
223                 {
224                   this.wait();
225                 }
226               catch (InterruptedException _)
227                 {
228                 }
229             }
230         }
231
232       // reconstruct the heap
233       TimerTask lastTask = heap[elements];
234       remove();
235
236       // drop lastTask at the beginning and move it down the heap
237       int parent = 1;
238       int child = 2;
239       heap[1] = lastTask;
240       while (child <= elements)
241         {
242           if (child < elements)
243             {
244               if (heap[child].scheduled > heap[child + 1].scheduled)
245                 {
246                   child++;
247                 }
248             }
249
250           if (lastTask.scheduled <= heap[child].scheduled)
251             break;              // found the correct place (the parent) - done
252
253           heap[parent] = heap[child];
254           parent = child;
255           child = parent * 2;
256         }
257
258       // this is the correct new place for the lastTask
259       heap[parent] = lastTask;
260
261       // return the task
262       return task;
263     }
264
265     /**
266      * When nullOnEmpty is true the serve() method will return null when
267      * there are no tasks in the queue, otherwise it will wait until
268      * a new element is added to the queue. It is used to indicate to
269      * the scheduler that no new tasks will ever be added to the queue.
270      */
271     public synchronized void setNullOnEmpty(boolean nullOnEmpty)
272     {
273       this.nullOnEmpty = nullOnEmpty;
274       this.notify();
275     }
276
277     /**
278      * When this method is called the current and all future calls to
279      * serve() will return null. It is used to indicate to the Scheduler
280      * that it should stop executing since no more tasks will come.
281      */
282     public synchronized void stop()
283     {
284       this.heap = null;
285       this.notify();
286     }
287
288   }                             // TaskQueue
289
290   /**
291    * The scheduler that executes all the tasks on a particular TaskQueue,
292    * reschedules any repeating tasks and that waits when no task has to be
293    * executed immediatly. Stops running when canceled or when the parent
294    * Timer has been finalized and no more tasks have to be executed.
295    */
296   private static final class Scheduler implements Runnable
297   {
298     // The priority queue containing all the TimerTasks.
299     private TaskQueue queue;
300
301     /**
302      * Creates a new Scheduler that will schedule the tasks on the
303      * given TaskQueue.
304      */
305     public Scheduler(TaskQueue queue)
306     {
307       this.queue = queue;
308     }
309
310     public void run()
311     {
312       TimerTask task;
313       while ((task = queue.serve()) != null)
314         {
315           // If this task has not been canceled
316           if (task.scheduled >= 0)
317             {
318
319               // Mark execution time
320               task.lastExecutionTime = task.scheduled;
321
322               // Repeatable task?
323               if (task.period < 0)
324                 {
325                   // Last time this task is executed
326                   task.scheduled = -1;
327                 }
328
329               // Run the task
330               try
331                 {
332                   task.run();
333                 }
334               catch (Throwable t)
335                 {               
336                   /* ignore all errors */
337                 }
338             }
339
340           // Calculate next time and possibly re-enqueue.
341           if (task.scheduled >= 0)
342             {
343               if (task.fixed)
344                 {
345                   task.scheduled += task.period;
346                 }
347               else
348                 {
349                   task.scheduled = task.period + System.currentTimeMillis();
350                 }
351
352               try
353                 {
354                   queue.enqueue(task);
355                 }
356               catch (IllegalStateException ise)
357                 {
358                   // Ignore. Apparently the Timer queue has been stopped.
359                 }
360             }
361         }
362     }
363   }                             // Scheduler
364
365   // Number of Timers created.
366   // Used for creating nice Thread names.
367   private static int nr = 0;
368
369   // The queue that all the tasks are put in.
370   // Given to the scheduler
371   private TaskQueue queue;
372
373   // The Scheduler that does all the real work
374   private Scheduler scheduler;
375
376   // Used to run the scheduler.
377   // Also used to checked if the Thread is still running by calling
378   // thread.isAlive(). Sometimes a Thread is suddenly killed by the system
379   // (if it belonged to an Applet).
380   private Thread thread;
381
382   // When cancelled we don't accept any more TimerTasks.
383   private boolean canceled;
384
385   /**
386    * Creates a new Timer with a non daemon Thread as Scheduler, with normal
387    * priority and a default name.
388    */
389   public Timer()
390   {
391     this(false);
392   }
393
394   /**
395    * Creates a new Timer with a daemon Thread as scheduler if daemon is true,
396    * with normal priority and a default name.
397    */
398   public Timer(boolean daemon)
399   {
400     this(daemon, Thread.NORM_PRIORITY);
401   }
402
403   /**
404    * Creates a new Timer with a daemon Thread as scheduler if daemon is true,
405    * with the priority given and a default name.
406    */
407   private Timer(boolean daemon, int priority)
408   {
409     this(daemon, priority, "Timer-" + (++nr));
410   }
411
412   /**
413    * Creates a new Timer with a daemon Thread as scheduler if daemon is true,
414    * with the priority and name given.E
415    */
416   private Timer(boolean daemon, int priority, String name)
417   {
418     canceled = false;
419     queue = new TaskQueue();
420     scheduler = new Scheduler(queue);
421     thread = new Thread(scheduler, name);
422     thread.setDaemon(daemon);
423     thread.setPriority(priority);
424     thread.start();
425   }
426
427   /**
428    * Cancels the execution of the scheduler. If a task is executing it will
429    * normally finish execution, but no other tasks will be executed and no
430    * more tasks can be scheduled.
431    */
432   public void cancel()
433   {
434     canceled = true;
435     queue.stop();
436   }
437
438   /**
439    * Schedules the task at Time time, repeating every period
440    * milliseconds if period is positive and at a fixed rate if fixed is true.
441    *
442    * @exception IllegalArgumentException if time is negative
443    * @exception IllegalStateException if the task was already scheduled or
444    * canceled or this Timer is canceled or the scheduler thread has died
445    */
446   private void schedule(TimerTask task, long time, long period, boolean fixed)
447   {
448     if (time < 0)
449       throw new IllegalArgumentException("negative time");
450
451     if (task.scheduled == 0 && task.lastExecutionTime == -1)
452       {
453         task.scheduled = time;
454         task.period = period;
455         task.fixed = fixed;
456       }
457     else
458       {
459         throw new IllegalStateException
460           ("task was already scheduled or canceled");
461       }
462
463     if (!this.canceled && this.thread != null)
464       {
465         queue.enqueue(task);
466       }
467     else
468       {
469         throw new IllegalStateException
470           ("timer was canceled or scheduler thread has died");
471       }
472   }
473
474   private static void positiveDelay(long delay)
475   {
476     if (delay < 0)
477       {
478         throw new IllegalArgumentException("delay is negative");
479       }
480   }
481
482   private static void positivePeriod(long period)
483   {
484     if (period < 0)
485       {
486         throw new IllegalArgumentException("period is negative");
487       }
488   }
489
490   /**
491    * Schedules the task at the specified data for one time execution.
492    *
493    * @exception IllegalArgumentException if date.getTime() is negative
494    * @exception IllegalStateException if the task was already scheduled or
495    * canceled or this Timer is canceled or the scheduler thread has died
496    */
497   public void schedule(TimerTask task, Date date)
498   {
499     long time = date.getTime();
500     schedule(task, time, -1, false);
501   }
502
503   /**
504    * Schedules the task at the specified date and reschedules the task every
505    * period milliseconds after the last execution of the task finishes until
506    * this timer or the task is canceled.
507    *
508    * @exception IllegalArgumentException if period or date.getTime() is
509    * negative
510    * @exception IllegalStateException if the task was already scheduled or
511    * canceled or this Timer is canceled or the scheduler thread has died
512    */
513   public void schedule(TimerTask task, Date date, long period)
514   {
515     positivePeriod(period);
516     long time = date.getTime();
517     schedule(task, time, period, false);
518   }
519
520   /**
521    * Schedules the task after the specified delay milliseconds for one time
522    * execution.
523    *
524    * @exception IllegalArgumentException if delay or
525    * System.currentTimeMillis + delay is negative
526    * @exception IllegalStateException if the task was already scheduled or
527    * canceled or this Timer is canceled or the scheduler thread has died
528    */
529   public void schedule(TimerTask task, long delay)
530   {
531     positiveDelay(delay);
532     long time = System.currentTimeMillis() + delay;
533     schedule(task, time, -1, false);
534   }
535
536   /**
537    * Schedules the task after the delay milliseconds and reschedules the
538    * task every period milliseconds after the last execution of the task
539    * finishes until this timer or the task is canceled.
540    *
541    * @exception IllegalArgumentException if delay or period is negative
542    * @exception IllegalStateException if the task was already scheduled or
543    * canceled or this Timer is canceled or the scheduler thread has died
544    */
545   public void schedule(TimerTask task, long delay, long period)
546   {
547     positiveDelay(delay);
548     positivePeriod(period);
549     long time = System.currentTimeMillis() + delay;
550     schedule(task, time, period, false);
551   }
552
553   /**
554    * Schedules the task at the specified date and reschedules the task at a
555    * fixed rate every period milliseconds until this timer or the task is
556    * canceled.
557    *
558    * @exception IllegalArgumentException if period or date.getTime() is
559    * negative
560    * @exception IllegalStateException if the task was already scheduled or
561    * canceled or this Timer is canceled or the scheduler thread has died
562    */
563   public void scheduleAtFixedRate(TimerTask task, Date date, long period)
564   {
565     positivePeriod(period);
566     long time = date.getTime();
567     schedule(task, time, period, true);
568   }
569
570   /**
571    * Schedules the task after the delay milliseconds and reschedules the task
572    * at a fixed rate every period milliseconds until this timer or the task
573    * is canceled.
574    *
575    * @exception IllegalArgumentException if delay or
576    * System.currentTimeMillis + delay is negative
577    * @exception IllegalStateException if the task was already scheduled or
578    * canceled or this Timer is canceled or the scheduler thread has died
579    */
580   public void scheduleAtFixedRate(TimerTask task, long delay, long period)
581   {
582     positiveDelay(delay);
583     positivePeriod(period);
584     long time = System.currentTimeMillis() + delay;
585     schedule(task, time, period, true);
586   }
587
588   /**
589    * Tells the scheduler that the Timer task died
590    * so there will be no more new tasks scheduled.
591    */
592   protected void finalize()
593   {
594     queue.setNullOnEmpty(true);
595   }
596 }