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