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