emul/compact/src/main/java/java/lang/Thread.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 07 Sep 2013 13:51:24 +0200
branchjdk7-b147
changeset 1258 724f3e1ea53e
permissions -rw-r--r--
Additional set of classes to make porting of lookup library more easier
jaroslav@1258
     1
/*
jaroslav@1258
     2
 * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
jaroslav@1258
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1258
     4
 *
jaroslav@1258
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@1258
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@1258
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@1258
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@1258
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1258
    10
 *
jaroslav@1258
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1258
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1258
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@1258
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1258
    15
 * accompanied this code).
jaroslav@1258
    16
 *
jaroslav@1258
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@1258
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1258
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1258
    20
 *
jaroslav@1258
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1258
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@1258
    23
 * questions.
jaroslav@1258
    24
 */
jaroslav@1258
    25
jaroslav@1258
    26
package java.lang;
jaroslav@1258
    27
jaroslav@1258
    28
import java.lang.ref.Reference;
jaroslav@1258
    29
import java.lang.ref.ReferenceQueue;
jaroslav@1258
    30
import java.lang.ref.WeakReference;
jaroslav@1258
    31
import java.security.AccessController;
jaroslav@1258
    32
import java.security.AccessControlContext;
jaroslav@1258
    33
import java.security.PrivilegedAction;
jaroslav@1258
    34
import java.util.Map;
jaroslav@1258
    35
import java.util.HashMap;
jaroslav@1258
    36
import java.util.concurrent.ConcurrentHashMap;
jaroslav@1258
    37
import java.util.concurrent.ConcurrentMap;
jaroslav@1258
    38
import java.util.concurrent.locks.LockSupport;
jaroslav@1258
    39
import sun.nio.ch.Interruptible;
jaroslav@1258
    40
import sun.security.util.SecurityConstants;
jaroslav@1258
    41
jaroslav@1258
    42
jaroslav@1258
    43
/**
jaroslav@1258
    44
 * A <i>thread</i> is a thread of execution in a program. The Java
jaroslav@1258
    45
 * Virtual Machine allows an application to have multiple threads of
jaroslav@1258
    46
 * execution running concurrently.
jaroslav@1258
    47
 * <p>
jaroslav@1258
    48
 * Every thread has a priority. Threads with higher priority are
jaroslav@1258
    49
 * executed in preference to threads with lower priority. Each thread
jaroslav@1258
    50
 * may or may not also be marked as a daemon. When code running in
jaroslav@1258
    51
 * some thread creates a new <code>Thread</code> object, the new
jaroslav@1258
    52
 * thread has its priority initially set equal to the priority of the
jaroslav@1258
    53
 * creating thread, and is a daemon thread if and only if the
jaroslav@1258
    54
 * creating thread is a daemon.
jaroslav@1258
    55
 * <p>
jaroslav@1258
    56
 * When a Java Virtual Machine starts up, there is usually a single
jaroslav@1258
    57
 * non-daemon thread (which typically calls the method named
jaroslav@1258
    58
 * <code>main</code> of some designated class). The Java Virtual
jaroslav@1258
    59
 * Machine continues to execute threads until either of the following
jaroslav@1258
    60
 * occurs:
jaroslav@1258
    61
 * <ul>
jaroslav@1258
    62
 * <li>The <code>exit</code> method of class <code>Runtime</code> has been
jaroslav@1258
    63
 *     called and the security manager has permitted the exit operation
jaroslav@1258
    64
 *     to take place.
jaroslav@1258
    65
 * <li>All threads that are not daemon threads have died, either by
jaroslav@1258
    66
 *     returning from the call to the <code>run</code> method or by
jaroslav@1258
    67
 *     throwing an exception that propagates beyond the <code>run</code>
jaroslav@1258
    68
 *     method.
jaroslav@1258
    69
 * </ul>
jaroslav@1258
    70
 * <p>
jaroslav@1258
    71
 * There are two ways to create a new thread of execution. One is to
jaroslav@1258
    72
 * declare a class to be a subclass of <code>Thread</code>. This
jaroslav@1258
    73
 * subclass should override the <code>run</code> method of class
jaroslav@1258
    74
 * <code>Thread</code>. An instance of the subclass can then be
jaroslav@1258
    75
 * allocated and started. For example, a thread that computes primes
jaroslav@1258
    76
 * larger than a stated value could be written as follows:
jaroslav@1258
    77
 * <p><hr><blockquote><pre>
jaroslav@1258
    78
 *     class PrimeThread extends Thread {
jaroslav@1258
    79
 *         long minPrime;
jaroslav@1258
    80
 *         PrimeThread(long minPrime) {
jaroslav@1258
    81
 *             this.minPrime = minPrime;
jaroslav@1258
    82
 *         }
jaroslav@1258
    83
 *
jaroslav@1258
    84
 *         public void run() {
jaroslav@1258
    85
 *             // compute primes larger than minPrime
jaroslav@1258
    86
 *             &nbsp;.&nbsp;.&nbsp;.
jaroslav@1258
    87
 *         }
jaroslav@1258
    88
 *     }
jaroslav@1258
    89
 * </pre></blockquote><hr>
jaroslav@1258
    90
 * <p>
jaroslav@1258
    91
 * The following code would then create a thread and start it running:
jaroslav@1258
    92
 * <p><blockquote><pre>
jaroslav@1258
    93
 *     PrimeThread p = new PrimeThread(143);
jaroslav@1258
    94
 *     p.start();
jaroslav@1258
    95
 * </pre></blockquote>
jaroslav@1258
    96
 * <p>
jaroslav@1258
    97
 * The other way to create a thread is to declare a class that
jaroslav@1258
    98
 * implements the <code>Runnable</code> interface. That class then
jaroslav@1258
    99
 * implements the <code>run</code> method. An instance of the class can
jaroslav@1258
   100
 * then be allocated, passed as an argument when creating
jaroslav@1258
   101
 * <code>Thread</code>, and started. The same example in this other
jaroslav@1258
   102
 * style looks like the following:
jaroslav@1258
   103
 * <p><hr><blockquote><pre>
jaroslav@1258
   104
 *     class PrimeRun implements Runnable {
jaroslav@1258
   105
 *         long minPrime;
jaroslav@1258
   106
 *         PrimeRun(long minPrime) {
jaroslav@1258
   107
 *             this.minPrime = minPrime;
jaroslav@1258
   108
 *         }
jaroslav@1258
   109
 *
jaroslav@1258
   110
 *         public void run() {
jaroslav@1258
   111
 *             // compute primes larger than minPrime
jaroslav@1258
   112
 *             &nbsp;.&nbsp;.&nbsp;.
jaroslav@1258
   113
 *         }
jaroslav@1258
   114
 *     }
jaroslav@1258
   115
 * </pre></blockquote><hr>
jaroslav@1258
   116
 * <p>
jaroslav@1258
   117
 * The following code would then create a thread and start it running:
jaroslav@1258
   118
 * <p><blockquote><pre>
jaroslav@1258
   119
 *     PrimeRun p = new PrimeRun(143);
jaroslav@1258
   120
 *     new Thread(p).start();
jaroslav@1258
   121
 * </pre></blockquote>
jaroslav@1258
   122
 * <p>
jaroslav@1258
   123
 * Every thread has a name for identification purposes. More than
jaroslav@1258
   124
 * one thread may have the same name. If a name is not specified when
jaroslav@1258
   125
 * a thread is created, a new name is generated for it.
jaroslav@1258
   126
 * <p>
jaroslav@1258
   127
 * Unless otherwise noted, passing a {@code null} argument to a constructor
jaroslav@1258
   128
 * or method in this class will cause a {@link NullPointerException} to be
jaroslav@1258
   129
 * thrown.
jaroslav@1258
   130
 *
jaroslav@1258
   131
 * @author  unascribed
jaroslav@1258
   132
 * @see     Runnable
jaroslav@1258
   133
 * @see     Runtime#exit(int)
jaroslav@1258
   134
 * @see     #run()
jaroslav@1258
   135
 * @see     #stop()
jaroslav@1258
   136
 * @since   JDK1.0
jaroslav@1258
   137
 */
jaroslav@1258
   138
public
jaroslav@1258
   139
class Thread implements Runnable {
jaroslav@1258
   140
    /* Make sure registerNatives is the first thing <clinit> does. */
jaroslav@1258
   141
    private static native void registerNatives();
jaroslav@1258
   142
    static {
jaroslav@1258
   143
        registerNatives();
jaroslav@1258
   144
    }
jaroslav@1258
   145
jaroslav@1258
   146
    private char        name[];
jaroslav@1258
   147
    private int         priority;
jaroslav@1258
   148
    private Thread      threadQ;
jaroslav@1258
   149
    private long        eetop;
jaroslav@1258
   150
jaroslav@1258
   151
    /* Whether or not to single_step this thread. */
jaroslav@1258
   152
    private boolean     single_step;
jaroslav@1258
   153
jaroslav@1258
   154
    /* Whether or not the thread is a daemon thread. */
jaroslav@1258
   155
    private boolean     daemon = false;
jaroslav@1258
   156
jaroslav@1258
   157
    /* JVM state */
jaroslav@1258
   158
    private boolean     stillborn = false;
jaroslav@1258
   159
jaroslav@1258
   160
    /* What will be run. */
jaroslav@1258
   161
    private Runnable target;
jaroslav@1258
   162
jaroslav@1258
   163
    /* The group of this thread */
jaroslav@1258
   164
    private ThreadGroup group;
jaroslav@1258
   165
jaroslav@1258
   166
    /* The context ClassLoader for this thread */
jaroslav@1258
   167
    private ClassLoader contextClassLoader;
jaroslav@1258
   168
jaroslav@1258
   169
    /* The inherited AccessControlContext of this thread */
jaroslav@1258
   170
    private AccessControlContext inheritedAccessControlContext;
jaroslav@1258
   171
jaroslav@1258
   172
    /* For autonumbering anonymous threads. */
jaroslav@1258
   173
    private static int threadInitNumber;
jaroslav@1258
   174
    private static synchronized int nextThreadNum() {
jaroslav@1258
   175
        return threadInitNumber++;
jaroslav@1258
   176
    }
jaroslav@1258
   177
jaroslav@1258
   178
    /* ThreadLocal values pertaining to this thread. This map is maintained
jaroslav@1258
   179
     * by the ThreadLocal class. */
jaroslav@1258
   180
    ThreadLocal.ThreadLocalMap threadLocals = null;
jaroslav@1258
   181
jaroslav@1258
   182
    /*
jaroslav@1258
   183
     * InheritableThreadLocal values pertaining to this thread. This map is
jaroslav@1258
   184
     * maintained by the InheritableThreadLocal class.
jaroslav@1258
   185
     */
jaroslav@1258
   186
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
jaroslav@1258
   187
jaroslav@1258
   188
    /*
jaroslav@1258
   189
     * The requested stack size for this thread, or 0 if the creator did
jaroslav@1258
   190
     * not specify a stack size.  It is up to the VM to do whatever it
jaroslav@1258
   191
     * likes with this number; some VMs will ignore it.
jaroslav@1258
   192
     */
jaroslav@1258
   193
    private long stackSize;
jaroslav@1258
   194
jaroslav@1258
   195
    /*
jaroslav@1258
   196
     * JVM-private state that persists after native thread termination.
jaroslav@1258
   197
     */
jaroslav@1258
   198
    private long nativeParkEventPointer;
jaroslav@1258
   199
jaroslav@1258
   200
    /*
jaroslav@1258
   201
     * Thread ID
jaroslav@1258
   202
     */
jaroslav@1258
   203
    private long tid;
jaroslav@1258
   204
jaroslav@1258
   205
    /* For generating thread ID */
jaroslav@1258
   206
    private static long threadSeqNumber;
jaroslav@1258
   207
jaroslav@1258
   208
    /* Java thread status for tools,
jaroslav@1258
   209
     * initialized to indicate thread 'not yet started'
jaroslav@1258
   210
     */
jaroslav@1258
   211
jaroslav@1258
   212
    private volatile int threadStatus = 0;
jaroslav@1258
   213
jaroslav@1258
   214
jaroslav@1258
   215
    private static synchronized long nextThreadID() {
jaroslav@1258
   216
        return ++threadSeqNumber;
jaroslav@1258
   217
    }
jaroslav@1258
   218
jaroslav@1258
   219
    /**
jaroslav@1258
   220
     * The argument supplied to the current call to
jaroslav@1258
   221
     * java.util.concurrent.locks.LockSupport.park.
jaroslav@1258
   222
     * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
jaroslav@1258
   223
     * Accessed using java.util.concurrent.locks.LockSupport.getBlocker
jaroslav@1258
   224
     */
jaroslav@1258
   225
    volatile Object parkBlocker;
jaroslav@1258
   226
jaroslav@1258
   227
    /* The object in which this thread is blocked in an interruptible I/O
jaroslav@1258
   228
     * operation, if any.  The blocker's interrupt method should be invoked
jaroslav@1258
   229
     * after setting this thread's interrupt status.
jaroslav@1258
   230
     */
jaroslav@1258
   231
    private volatile Interruptible blocker;
jaroslav@1258
   232
    private final Object blockerLock = new Object();
jaroslav@1258
   233
jaroslav@1258
   234
    /* Set the blocker field; invoked via sun.misc.SharedSecrets from java.nio code
jaroslav@1258
   235
     */
jaroslav@1258
   236
    void blockedOn(Interruptible b) {
jaroslav@1258
   237
        synchronized (blockerLock) {
jaroslav@1258
   238
            blocker = b;
jaroslav@1258
   239
        }
jaroslav@1258
   240
    }
jaroslav@1258
   241
jaroslav@1258
   242
    /**
jaroslav@1258
   243
     * The minimum priority that a thread can have.
jaroslav@1258
   244
     */
jaroslav@1258
   245
    public final static int MIN_PRIORITY = 1;
jaroslav@1258
   246
jaroslav@1258
   247
   /**
jaroslav@1258
   248
     * The default priority that is assigned to a thread.
jaroslav@1258
   249
     */
jaroslav@1258
   250
    public final static int NORM_PRIORITY = 5;
jaroslav@1258
   251
jaroslav@1258
   252
    /**
jaroslav@1258
   253
     * The maximum priority that a thread can have.
jaroslav@1258
   254
     */
jaroslav@1258
   255
    public final static int MAX_PRIORITY = 10;
jaroslav@1258
   256
jaroslav@1258
   257
    /**
jaroslav@1258
   258
     * Returns a reference to the currently executing thread object.
jaroslav@1258
   259
     *
jaroslav@1258
   260
     * @return  the currently executing thread.
jaroslav@1258
   261
     */
jaroslav@1258
   262
    public static native Thread currentThread();
jaroslav@1258
   263
jaroslav@1258
   264
    /**
jaroslav@1258
   265
     * A hint to the scheduler that the current thread is willing to yield
jaroslav@1258
   266
     * its current use of a processor. The scheduler is free to ignore this
jaroslav@1258
   267
     * hint.
jaroslav@1258
   268
     *
jaroslav@1258
   269
     * <p> Yield is a heuristic attempt to improve relative progression
jaroslav@1258
   270
     * between threads that would otherwise over-utilise a CPU. Its use
jaroslav@1258
   271
     * should be combined with detailed profiling and benchmarking to
jaroslav@1258
   272
     * ensure that it actually has the desired effect.
jaroslav@1258
   273
     *
jaroslav@1258
   274
     * <p> It is rarely appropriate to use this method. It may be useful
jaroslav@1258
   275
     * for debugging or testing purposes, where it may help to reproduce
jaroslav@1258
   276
     * bugs due to race conditions. It may also be useful when designing
jaroslav@1258
   277
     * concurrency control constructs such as the ones in the
jaroslav@1258
   278
     * {@link java.util.concurrent.locks} package.
jaroslav@1258
   279
     */
jaroslav@1258
   280
    public static native void yield();
jaroslav@1258
   281
jaroslav@1258
   282
    /**
jaroslav@1258
   283
     * Causes the currently executing thread to sleep (temporarily cease
jaroslav@1258
   284
     * execution) for the specified number of milliseconds, subject to
jaroslav@1258
   285
     * the precision and accuracy of system timers and schedulers. The thread
jaroslav@1258
   286
     * does not lose ownership of any monitors.
jaroslav@1258
   287
     *
jaroslav@1258
   288
     * @param  millis
jaroslav@1258
   289
     *         the length of time to sleep in milliseconds
jaroslav@1258
   290
     *
jaroslav@1258
   291
     * @throws  IllegalArgumentException
jaroslav@1258
   292
     *          if the value of {@code millis} is negative
jaroslav@1258
   293
     *
jaroslav@1258
   294
     * @throws  InterruptedException
jaroslav@1258
   295
     *          if any thread has interrupted the current thread. The
jaroslav@1258
   296
     *          <i>interrupted status</i> of the current thread is
jaroslav@1258
   297
     *          cleared when this exception is thrown.
jaroslav@1258
   298
     */
jaroslav@1258
   299
    public static native void sleep(long millis) throws InterruptedException;
jaroslav@1258
   300
jaroslav@1258
   301
    /**
jaroslav@1258
   302
     * Causes the currently executing thread to sleep (temporarily cease
jaroslav@1258
   303
     * execution) for the specified number of milliseconds plus the specified
jaroslav@1258
   304
     * number of nanoseconds, subject to the precision and accuracy of system
jaroslav@1258
   305
     * timers and schedulers. The thread does not lose ownership of any
jaroslav@1258
   306
     * monitors.
jaroslav@1258
   307
     *
jaroslav@1258
   308
     * @param  millis
jaroslav@1258
   309
     *         the length of time to sleep in milliseconds
jaroslav@1258
   310
     *
jaroslav@1258
   311
     * @param  nanos
jaroslav@1258
   312
     *         {@code 0-999999} additional nanoseconds to sleep
jaroslav@1258
   313
     *
jaroslav@1258
   314
     * @throws  IllegalArgumentException
jaroslav@1258
   315
     *          if the value of {@code millis} is negative, or the value of
jaroslav@1258
   316
     *          {@code nanos} is not in the range {@code 0-999999}
jaroslav@1258
   317
     *
jaroslav@1258
   318
     * @throws  InterruptedException
jaroslav@1258
   319
     *          if any thread has interrupted the current thread. The
jaroslav@1258
   320
     *          <i>interrupted status</i> of the current thread is
jaroslav@1258
   321
     *          cleared when this exception is thrown.
jaroslav@1258
   322
     */
jaroslav@1258
   323
    public static void sleep(long millis, int nanos)
jaroslav@1258
   324
    throws InterruptedException {
jaroslav@1258
   325
        if (millis < 0) {
jaroslav@1258
   326
            throw new IllegalArgumentException("timeout value is negative");
jaroslav@1258
   327
        }
jaroslav@1258
   328
jaroslav@1258
   329
        if (nanos < 0 || nanos > 999999) {
jaroslav@1258
   330
            throw new IllegalArgumentException(
jaroslav@1258
   331
                                "nanosecond timeout value out of range");
jaroslav@1258
   332
        }
jaroslav@1258
   333
jaroslav@1258
   334
        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
jaroslav@1258
   335
            millis++;
jaroslav@1258
   336
        }
jaroslav@1258
   337
jaroslav@1258
   338
        sleep(millis);
jaroslav@1258
   339
    }
jaroslav@1258
   340
jaroslav@1258
   341
    /**
jaroslav@1258
   342
     * Initializes a Thread.
jaroslav@1258
   343
     *
jaroslav@1258
   344
     * @param g the Thread group
jaroslav@1258
   345
     * @param target the object whose run() method gets called
jaroslav@1258
   346
     * @param name the name of the new Thread
jaroslav@1258
   347
     * @param stackSize the desired stack size for the new thread, or
jaroslav@1258
   348
     *        zero to indicate that this parameter is to be ignored.
jaroslav@1258
   349
     */
jaroslav@1258
   350
    private void init(ThreadGroup g, Runnable target, String name,
jaroslav@1258
   351
                      long stackSize) {
jaroslav@1258
   352
        if (name == null) {
jaroslav@1258
   353
            throw new NullPointerException("name cannot be null");
jaroslav@1258
   354
        }
jaroslav@1258
   355
jaroslav@1258
   356
        Thread parent = currentThread();
jaroslav@1258
   357
        SecurityManager security = System.getSecurityManager();
jaroslav@1258
   358
        if (g == null) {
jaroslav@1258
   359
            /* Determine if it's an applet or not */
jaroslav@1258
   360
jaroslav@1258
   361
            /* If there is a security manager, ask the security manager
jaroslav@1258
   362
               what to do. */
jaroslav@1258
   363
            if (security != null) {
jaroslav@1258
   364
                g = security.getThreadGroup();
jaroslav@1258
   365
            }
jaroslav@1258
   366
jaroslav@1258
   367
            /* If the security doesn't have a strong opinion of the matter
jaroslav@1258
   368
               use the parent thread group. */
jaroslav@1258
   369
            if (g == null) {
jaroslav@1258
   370
                g = parent.getThreadGroup();
jaroslav@1258
   371
            }
jaroslav@1258
   372
        }
jaroslav@1258
   373
jaroslav@1258
   374
        /* checkAccess regardless of whether or not threadgroup is
jaroslav@1258
   375
           explicitly passed in. */
jaroslav@1258
   376
        g.checkAccess();
jaroslav@1258
   377
jaroslav@1258
   378
        /*
jaroslav@1258
   379
         * Do we have the required permissions?
jaroslav@1258
   380
         */
jaroslav@1258
   381
        if (security != null) {
jaroslav@1258
   382
            if (isCCLOverridden(getClass())) {
jaroslav@1258
   383
                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
jaroslav@1258
   384
            }
jaroslav@1258
   385
        }
jaroslav@1258
   386
jaroslav@1258
   387
        g.addUnstarted();
jaroslav@1258
   388
jaroslav@1258
   389
        this.group = g;
jaroslav@1258
   390
        this.daemon = parent.isDaemon();
jaroslav@1258
   391
        this.priority = parent.getPriority();
jaroslav@1258
   392
        this.name = name.toCharArray();
jaroslav@1258
   393
        if (security == null || isCCLOverridden(parent.getClass()))
jaroslav@1258
   394
            this.contextClassLoader = parent.getContextClassLoader();
jaroslav@1258
   395
        else
jaroslav@1258
   396
            this.contextClassLoader = parent.contextClassLoader;
jaroslav@1258
   397
        this.inheritedAccessControlContext = AccessController.getContext();
jaroslav@1258
   398
        this.target = target;
jaroslav@1258
   399
        setPriority(priority);
jaroslav@1258
   400
        if (parent.inheritableThreadLocals != null)
jaroslav@1258
   401
            this.inheritableThreadLocals =
jaroslav@1258
   402
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
jaroslav@1258
   403
        /* Stash the specified stack size in case the VM cares */
jaroslav@1258
   404
        this.stackSize = stackSize;
jaroslav@1258
   405
jaroslav@1258
   406
        /* Set thread ID */
jaroslav@1258
   407
        tid = nextThreadID();
jaroslav@1258
   408
    }
jaroslav@1258
   409
jaroslav@1258
   410
    /**
jaroslav@1258
   411
     * Throws CloneNotSupportedException as a Thread can not be meaningfully
jaroslav@1258
   412
     * cloned. Construct a new Thread instead.
jaroslav@1258
   413
     *
jaroslav@1258
   414
     * @throws  CloneNotSupportedException
jaroslav@1258
   415
     *          always
jaroslav@1258
   416
     */
jaroslav@1258
   417
    @Override
jaroslav@1258
   418
    protected Object clone() throws CloneNotSupportedException {
jaroslav@1258
   419
        throw new CloneNotSupportedException();
jaroslav@1258
   420
    }
jaroslav@1258
   421
jaroslav@1258
   422
    /**
jaroslav@1258
   423
     * Allocates a new {@code Thread} object. This constructor has the same
jaroslav@1258
   424
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
jaroslav@1258
   425
     * {@code (null, null, gname)}, where {@code gname} is a newly generated
jaroslav@1258
   426
     * name. Automatically generated names are of the form
jaroslav@1258
   427
     * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
jaroslav@1258
   428
     */
jaroslav@1258
   429
    public Thread() {
jaroslav@1258
   430
        init(null, null, "Thread-" + nextThreadNum(), 0);
jaroslav@1258
   431
    }
jaroslav@1258
   432
jaroslav@1258
   433
    /**
jaroslav@1258
   434
     * Allocates a new {@code Thread} object. This constructor has the same
jaroslav@1258
   435
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
jaroslav@1258
   436
     * {@code (null, target, gname)}, where {@code gname} is a newly generated
jaroslav@1258
   437
     * name. Automatically generated names are of the form
jaroslav@1258
   438
     * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
jaroslav@1258
   439
     *
jaroslav@1258
   440
     * @param  target
jaroslav@1258
   441
     *         the object whose {@code run} method is invoked when this thread
jaroslav@1258
   442
     *         is started. If {@code null}, this classes {@code run} method does
jaroslav@1258
   443
     *         nothing.
jaroslav@1258
   444
     */
jaroslav@1258
   445
    public Thread(Runnable target) {
jaroslav@1258
   446
        init(null, target, "Thread-" + nextThreadNum(), 0);
jaroslav@1258
   447
    }
jaroslav@1258
   448
jaroslav@1258
   449
    /**
jaroslav@1258
   450
     * Allocates a new {@code Thread} object. This constructor has the same
jaroslav@1258
   451
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
jaroslav@1258
   452
     * {@code (group, target, gname)} ,where {@code gname} is a newly generated
jaroslav@1258
   453
     * name. Automatically generated names are of the form
jaroslav@1258
   454
     * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
jaroslav@1258
   455
     *
jaroslav@1258
   456
     * @param  group
jaroslav@1258
   457
     *         the thread group. If {@code null} and there is a security
jaroslav@1258
   458
     *         manager, the group is determined by {@linkplain
jaroslav@1258
   459
     *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
jaroslav@1258
   460
     *         If there is not a security manager or {@code
jaroslav@1258
   461
     *         SecurityManager.getThreadGroup()} returns {@code null}, the group
jaroslav@1258
   462
     *         is set to the current thread's thread group.
jaroslav@1258
   463
     *
jaroslav@1258
   464
     * @param  target
jaroslav@1258
   465
     *         the object whose {@code run} method is invoked when this thread
jaroslav@1258
   466
     *         is started. If {@code null}, this thread's run method is invoked.
jaroslav@1258
   467
     *
jaroslav@1258
   468
     * @throws  SecurityException
jaroslav@1258
   469
     *          if the current thread cannot create a thread in the specified
jaroslav@1258
   470
     *          thread group
jaroslav@1258
   471
     */
jaroslav@1258
   472
    public Thread(ThreadGroup group, Runnable target) {
jaroslav@1258
   473
        init(group, target, "Thread-" + nextThreadNum(), 0);
jaroslav@1258
   474
    }
jaroslav@1258
   475
jaroslav@1258
   476
    /**
jaroslav@1258
   477
     * Allocates a new {@code Thread} object. This constructor has the same
jaroslav@1258
   478
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
jaroslav@1258
   479
     * {@code (null, null, name)}.
jaroslav@1258
   480
     *
jaroslav@1258
   481
     * @param   name
jaroslav@1258
   482
     *          the name of the new thread
jaroslav@1258
   483
     */
jaroslav@1258
   484
    public Thread(String name) {
jaroslav@1258
   485
        init(null, null, name, 0);
jaroslav@1258
   486
    }
jaroslav@1258
   487
jaroslav@1258
   488
    /**
jaroslav@1258
   489
     * Allocates a new {@code Thread} object. This constructor has the same
jaroslav@1258
   490
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
jaroslav@1258
   491
     * {@code (group, null, name)}.
jaroslav@1258
   492
     *
jaroslav@1258
   493
     * @param  group
jaroslav@1258
   494
     *         the thread group. If {@code null} and there is a security
jaroslav@1258
   495
     *         manager, the group is determined by {@linkplain
jaroslav@1258
   496
     *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
jaroslav@1258
   497
     *         If there is not a security manager or {@code
jaroslav@1258
   498
     *         SecurityManager.getThreadGroup()} returns {@code null}, the group
jaroslav@1258
   499
     *         is set to the current thread's thread group.
jaroslav@1258
   500
     *
jaroslav@1258
   501
     * @param  name
jaroslav@1258
   502
     *         the name of the new thread
jaroslav@1258
   503
     *
jaroslav@1258
   504
     * @throws  SecurityException
jaroslav@1258
   505
     *          if the current thread cannot create a thread in the specified
jaroslav@1258
   506
     *          thread group
jaroslav@1258
   507
     */
jaroslav@1258
   508
    public Thread(ThreadGroup group, String name) {
jaroslav@1258
   509
        init(group, null, name, 0);
jaroslav@1258
   510
    }
jaroslav@1258
   511
jaroslav@1258
   512
    /**
jaroslav@1258
   513
     * Allocates a new {@code Thread} object. This constructor has the same
jaroslav@1258
   514
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
jaroslav@1258
   515
     * {@code (null, target, name)}.
jaroslav@1258
   516
     *
jaroslav@1258
   517
     * @param  target
jaroslav@1258
   518
     *         the object whose {@code run} method is invoked when this thread
jaroslav@1258
   519
     *         is started. If {@code null}, this thread's run method is invoked.
jaroslav@1258
   520
     *
jaroslav@1258
   521
     * @param  name
jaroslav@1258
   522
     *         the name of the new thread
jaroslav@1258
   523
     */
jaroslav@1258
   524
    public Thread(Runnable target, String name) {
jaroslav@1258
   525
        init(null, target, name, 0);
jaroslav@1258
   526
    }
jaroslav@1258
   527
jaroslav@1258
   528
    /**
jaroslav@1258
   529
     * Allocates a new {@code Thread} object so that it has {@code target}
jaroslav@1258
   530
     * as its run object, has the specified {@code name} as its name,
jaroslav@1258
   531
     * and belongs to the thread group referred to by {@code group}.
jaroslav@1258
   532
     *
jaroslav@1258
   533
     * <p>If there is a security manager, its
jaroslav@1258
   534
     * {@link SecurityManager#checkAccess(ThreadGroup) checkAccess}
jaroslav@1258
   535
     * method is invoked with the ThreadGroup as its argument.
jaroslav@1258
   536
     *
jaroslav@1258
   537
     * <p>In addition, its {@code checkPermission} method is invoked with
jaroslav@1258
   538
     * the {@code RuntimePermission("enableContextClassLoaderOverride")}
jaroslav@1258
   539
     * permission when invoked directly or indirectly by the constructor
jaroslav@1258
   540
     * of a subclass which overrides the {@code getContextClassLoader}
jaroslav@1258
   541
     * or {@code setContextClassLoader} methods.
jaroslav@1258
   542
     *
jaroslav@1258
   543
     * <p>The priority of the newly created thread is set equal to the
jaroslav@1258
   544
     * priority of the thread creating it, that is, the currently running
jaroslav@1258
   545
     * thread. The method {@linkplain #setPriority setPriority} may be
jaroslav@1258
   546
     * used to change the priority to a new value.
jaroslav@1258
   547
     *
jaroslav@1258
   548
     * <p>The newly created thread is initially marked as being a daemon
jaroslav@1258
   549
     * thread if and only if the thread creating it is currently marked
jaroslav@1258
   550
     * as a daemon thread. The method {@linkplain #setDaemon setDaemon}
jaroslav@1258
   551
     * may be used to change whether or not a thread is a daemon.
jaroslav@1258
   552
     *
jaroslav@1258
   553
     * @param  group
jaroslav@1258
   554
     *         the thread group. If {@code null} and there is a security
jaroslav@1258
   555
     *         manager, the group is determined by {@linkplain
jaroslav@1258
   556
     *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
jaroslav@1258
   557
     *         If there is not a security manager or {@code
jaroslav@1258
   558
     *         SecurityManager.getThreadGroup()} returns {@code null}, the group
jaroslav@1258
   559
     *         is set to the current thread's thread group.
jaroslav@1258
   560
     *
jaroslav@1258
   561
     * @param  target
jaroslav@1258
   562
     *         the object whose {@code run} method is invoked when this thread
jaroslav@1258
   563
     *         is started. If {@code null}, this thread's run method is invoked.
jaroslav@1258
   564
     *
jaroslav@1258
   565
     * @param  name
jaroslav@1258
   566
     *         the name of the new thread
jaroslav@1258
   567
     *
jaroslav@1258
   568
     * @throws  SecurityException
jaroslav@1258
   569
     *          if the current thread cannot create a thread in the specified
jaroslav@1258
   570
     *          thread group or cannot override the context class loader methods.
jaroslav@1258
   571
     */
jaroslav@1258
   572
    public Thread(ThreadGroup group, Runnable target, String name) {
jaroslav@1258
   573
        init(group, target, name, 0);
jaroslav@1258
   574
    }
jaroslav@1258
   575
jaroslav@1258
   576
    /**
jaroslav@1258
   577
     * Allocates a new {@code Thread} object so that it has {@code target}
jaroslav@1258
   578
     * as its run object, has the specified {@code name} as its name,
jaroslav@1258
   579
     * and belongs to the thread group referred to by {@code group}, and has
jaroslav@1258
   580
     * the specified <i>stack size</i>.
jaroslav@1258
   581
     *
jaroslav@1258
   582
     * <p>This constructor is identical to {@link
jaroslav@1258
   583
     * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact
jaroslav@1258
   584
     * that it allows the thread stack size to be specified.  The stack size
jaroslav@1258
   585
     * is the approximate number of bytes of address space that the virtual
jaroslav@1258
   586
     * machine is to allocate for this thread's stack.  <b>The effect of the
jaroslav@1258
   587
     * {@code stackSize} parameter, if any, is highly platform dependent.</b>
jaroslav@1258
   588
     *
jaroslav@1258
   589
     * <p>On some platforms, specifying a higher value for the
jaroslav@1258
   590
     * {@code stackSize} parameter may allow a thread to achieve greater
jaroslav@1258
   591
     * recursion depth before throwing a {@link StackOverflowError}.
jaroslav@1258
   592
     * Similarly, specifying a lower value may allow a greater number of
jaroslav@1258
   593
     * threads to exist concurrently without throwing an {@link
jaroslav@1258
   594
     * OutOfMemoryError} (or other internal error).  The details of
jaroslav@1258
   595
     * the relationship between the value of the <tt>stackSize</tt> parameter
jaroslav@1258
   596
     * and the maximum recursion depth and concurrency level are
jaroslav@1258
   597
     * platform-dependent.  <b>On some platforms, the value of the
jaroslav@1258
   598
     * {@code stackSize} parameter may have no effect whatsoever.</b>
jaroslav@1258
   599
     *
jaroslav@1258
   600
     * <p>The virtual machine is free to treat the {@code stackSize}
jaroslav@1258
   601
     * parameter as a suggestion.  If the specified value is unreasonably low
jaroslav@1258
   602
     * for the platform, the virtual machine may instead use some
jaroslav@1258
   603
     * platform-specific minimum value; if the specified value is unreasonably
jaroslav@1258
   604
     * high, the virtual machine may instead use some platform-specific
jaroslav@1258
   605
     * maximum.  Likewise, the virtual machine is free to round the specified
jaroslav@1258
   606
     * value up or down as it sees fit (or to ignore it completely).
jaroslav@1258
   607
     *
jaroslav@1258
   608
     * <p>Specifying a value of zero for the {@code stackSize} parameter will
jaroslav@1258
   609
     * cause this constructor to behave exactly like the
jaroslav@1258
   610
     * {@code Thread(ThreadGroup, Runnable, String)} constructor.
jaroslav@1258
   611
     *
jaroslav@1258
   612
     * <p><i>Due to the platform-dependent nature of the behavior of this
jaroslav@1258
   613
     * constructor, extreme care should be exercised in its use.
jaroslav@1258
   614
     * The thread stack size necessary to perform a given computation will
jaroslav@1258
   615
     * likely vary from one JRE implementation to another.  In light of this
jaroslav@1258
   616
     * variation, careful tuning of the stack size parameter may be required,
jaroslav@1258
   617
     * and the tuning may need to be repeated for each JRE implementation on
jaroslav@1258
   618
     * which an application is to run.</i>
jaroslav@1258
   619
     *
jaroslav@1258
   620
     * <p>Implementation note: Java platform implementers are encouraged to
jaroslav@1258
   621
     * document their implementation's behavior with respect to the
jaroslav@1258
   622
     * {@code stackSize} parameter.
jaroslav@1258
   623
     *
jaroslav@1258
   624
     *
jaroslav@1258
   625
     * @param  group
jaroslav@1258
   626
     *         the thread group. If {@code null} and there is a security
jaroslav@1258
   627
     *         manager, the group is determined by {@linkplain
jaroslav@1258
   628
     *         SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
jaroslav@1258
   629
     *         If there is not a security manager or {@code
jaroslav@1258
   630
     *         SecurityManager.getThreadGroup()} returns {@code null}, the group
jaroslav@1258
   631
     *         is set to the current thread's thread group.
jaroslav@1258
   632
     *
jaroslav@1258
   633
     * @param  target
jaroslav@1258
   634
     *         the object whose {@code run} method is invoked when this thread
jaroslav@1258
   635
     *         is started. If {@code null}, this thread's run method is invoked.
jaroslav@1258
   636
     *
jaroslav@1258
   637
     * @param  name
jaroslav@1258
   638
     *         the name of the new thread
jaroslav@1258
   639
     *
jaroslav@1258
   640
     * @param  stackSize
jaroslav@1258
   641
     *         the desired stack size for the new thread, or zero to indicate
jaroslav@1258
   642
     *         that this parameter is to be ignored.
jaroslav@1258
   643
     *
jaroslav@1258
   644
     * @throws  SecurityException
jaroslav@1258
   645
     *          if the current thread cannot create a thread in the specified
jaroslav@1258
   646
     *          thread group
jaroslav@1258
   647
     *
jaroslav@1258
   648
     * @since 1.4
jaroslav@1258
   649
     */
jaroslav@1258
   650
    public Thread(ThreadGroup group, Runnable target, String name,
jaroslav@1258
   651
                  long stackSize) {
jaroslav@1258
   652
        init(group, target, name, stackSize);
jaroslav@1258
   653
    }
jaroslav@1258
   654
jaroslav@1258
   655
    /**
jaroslav@1258
   656
     * Causes this thread to begin execution; the Java Virtual Machine
jaroslav@1258
   657
     * calls the <code>run</code> method of this thread.
jaroslav@1258
   658
     * <p>
jaroslav@1258
   659
     * The result is that two threads are running concurrently: the
jaroslav@1258
   660
     * current thread (which returns from the call to the
jaroslav@1258
   661
     * <code>start</code> method) and the other thread (which executes its
jaroslav@1258
   662
     * <code>run</code> method).
jaroslav@1258
   663
     * <p>
jaroslav@1258
   664
     * It is never legal to start a thread more than once.
jaroslav@1258
   665
     * In particular, a thread may not be restarted once it has completed
jaroslav@1258
   666
     * execution.
jaroslav@1258
   667
     *
jaroslav@1258
   668
     * @exception  IllegalThreadStateException  if the thread was already
jaroslav@1258
   669
     *               started.
jaroslav@1258
   670
     * @see        #run()
jaroslav@1258
   671
     * @see        #stop()
jaroslav@1258
   672
     */
jaroslav@1258
   673
    public synchronized void start() {
jaroslav@1258
   674
        /**
jaroslav@1258
   675
         * This method is not invoked for the main method thread or "system"
jaroslav@1258
   676
         * group threads created/set up by the VM. Any new functionality added
jaroslav@1258
   677
         * to this method in the future may have to also be added to the VM.
jaroslav@1258
   678
         *
jaroslav@1258
   679
         * A zero status value corresponds to state "NEW".
jaroslav@1258
   680
         */
jaroslav@1258
   681
        if (threadStatus != 0)
jaroslav@1258
   682
            throw new IllegalThreadStateException();
jaroslav@1258
   683
jaroslav@1258
   684
        /* Notify the group that this thread is about to be started
jaroslav@1258
   685
         * so that it can be added to the group's list of threads
jaroslav@1258
   686
         * and the group's unstarted count can be decremented. */
jaroslav@1258
   687
        group.add(this);
jaroslav@1258
   688
jaroslav@1258
   689
        boolean started = false;
jaroslav@1258
   690
        try {
jaroslav@1258
   691
            start0();
jaroslav@1258
   692
            started = true;
jaroslav@1258
   693
        } finally {
jaroslav@1258
   694
            try {
jaroslav@1258
   695
                if (!started) {
jaroslav@1258
   696
                    group.threadStartFailed(this);
jaroslav@1258
   697
                }
jaroslav@1258
   698
            } catch (Throwable ignore) {
jaroslav@1258
   699
                /* do nothing. If start0 threw a Throwable then
jaroslav@1258
   700
                  it will be passed up the call stack */
jaroslav@1258
   701
            }
jaroslav@1258
   702
        }
jaroslav@1258
   703
    }
jaroslav@1258
   704
jaroslav@1258
   705
    private native void start0();
jaroslav@1258
   706
jaroslav@1258
   707
    /**
jaroslav@1258
   708
     * If this thread was constructed using a separate
jaroslav@1258
   709
     * <code>Runnable</code> run object, then that
jaroslav@1258
   710
     * <code>Runnable</code> object's <code>run</code> method is called;
jaroslav@1258
   711
     * otherwise, this method does nothing and returns.
jaroslav@1258
   712
     * <p>
jaroslav@1258
   713
     * Subclasses of <code>Thread</code> should override this method.
jaroslav@1258
   714
     *
jaroslav@1258
   715
     * @see     #start()
jaroslav@1258
   716
     * @see     #stop()
jaroslav@1258
   717
     * @see     #Thread(ThreadGroup, Runnable, String)
jaroslav@1258
   718
     */
jaroslav@1258
   719
    @Override
jaroslav@1258
   720
    public void run() {
jaroslav@1258
   721
        if (target != null) {
jaroslav@1258
   722
            target.run();
jaroslav@1258
   723
        }
jaroslav@1258
   724
    }
jaroslav@1258
   725
jaroslav@1258
   726
    /**
jaroslav@1258
   727
     * This method is called by the system to give a Thread
jaroslav@1258
   728
     * a chance to clean up before it actually exits.
jaroslav@1258
   729
     */
jaroslav@1258
   730
    private void exit() {
jaroslav@1258
   731
        if (group != null) {
jaroslav@1258
   732
            group.threadTerminated(this);
jaroslav@1258
   733
            group = null;
jaroslav@1258
   734
        }
jaroslav@1258
   735
        /* Aggressively null out all reference fields: see bug 4006245 */
jaroslav@1258
   736
        target = null;
jaroslav@1258
   737
        /* Speed the release of some of these resources */
jaroslav@1258
   738
        threadLocals = null;
jaroslav@1258
   739
        inheritableThreadLocals = null;
jaroslav@1258
   740
        inheritedAccessControlContext = null;
jaroslav@1258
   741
        blocker = null;
jaroslav@1258
   742
        uncaughtExceptionHandler = null;
jaroslav@1258
   743
    }
jaroslav@1258
   744
jaroslav@1258
   745
    /**
jaroslav@1258
   746
     * Forces the thread to stop executing.
jaroslav@1258
   747
     * <p>
jaroslav@1258
   748
     * If there is a security manager installed, its <code>checkAccess</code>
jaroslav@1258
   749
     * method is called with <code>this</code>
jaroslav@1258
   750
     * as its argument. This may result in a
jaroslav@1258
   751
     * <code>SecurityException</code> being raised (in the current thread).
jaroslav@1258
   752
     * <p>
jaroslav@1258
   753
     * If this thread is different from the current thread (that is, the current
jaroslav@1258
   754
     * thread is trying to stop a thread other than itself), the
jaroslav@1258
   755
     * security manager's <code>checkPermission</code> method (with a
jaroslav@1258
   756
     * <code>RuntimePermission("stopThread")</code> argument) is called in
jaroslav@1258
   757
     * addition.
jaroslav@1258
   758
     * Again, this may result in throwing a
jaroslav@1258
   759
     * <code>SecurityException</code> (in the current thread).
jaroslav@1258
   760
     * <p>
jaroslav@1258
   761
     * The thread represented by this thread is forced to stop whatever
jaroslav@1258
   762
     * it is doing abnormally and to throw a newly created
jaroslav@1258
   763
     * <code>ThreadDeath</code> object as an exception.
jaroslav@1258
   764
     * <p>
jaroslav@1258
   765
     * It is permitted to stop a thread that has not yet been started.
jaroslav@1258
   766
     * If the thread is eventually started, it immediately terminates.
jaroslav@1258
   767
     * <p>
jaroslav@1258
   768
     * An application should not normally try to catch
jaroslav@1258
   769
     * <code>ThreadDeath</code> unless it must do some extraordinary
jaroslav@1258
   770
     * cleanup operation (note that the throwing of
jaroslav@1258
   771
     * <code>ThreadDeath</code> causes <code>finally</code> clauses of
jaroslav@1258
   772
     * <code>try</code> statements to be executed before the thread
jaroslav@1258
   773
     * officially dies).  If a <code>catch</code> clause catches a
jaroslav@1258
   774
     * <code>ThreadDeath</code> object, it is important to rethrow the
jaroslav@1258
   775
     * object so that the thread actually dies.
jaroslav@1258
   776
     * <p>
jaroslav@1258
   777
     * The top-level error handler that reacts to otherwise uncaught
jaroslav@1258
   778
     * exceptions does not print out a message or otherwise notify the
jaroslav@1258
   779
     * application if the uncaught exception is an instance of
jaroslav@1258
   780
     * <code>ThreadDeath</code>.
jaroslav@1258
   781
     *
jaroslav@1258
   782
     * @exception  SecurityException  if the current thread cannot
jaroslav@1258
   783
     *               modify this thread.
jaroslav@1258
   784
     * @see        #interrupt()
jaroslav@1258
   785
     * @see        #checkAccess()
jaroslav@1258
   786
     * @see        #run()
jaroslav@1258
   787
     * @see        #start()
jaroslav@1258
   788
     * @see        ThreadDeath
jaroslav@1258
   789
     * @see        ThreadGroup#uncaughtException(Thread,Throwable)
jaroslav@1258
   790
     * @see        SecurityManager#checkAccess(Thread)
jaroslav@1258
   791
     * @see        SecurityManager#checkPermission
jaroslav@1258
   792
     * @deprecated This method is inherently unsafe.  Stopping a thread with
jaroslav@1258
   793
     *       Thread.stop causes it to unlock all of the monitors that it
jaroslav@1258
   794
     *       has locked (as a natural consequence of the unchecked
jaroslav@1258
   795
     *       <code>ThreadDeath</code> exception propagating up the stack).  If
jaroslav@1258
   796
     *       any of the objects previously protected by these monitors were in
jaroslav@1258
   797
     *       an inconsistent state, the damaged objects become visible to
jaroslav@1258
   798
     *       other threads, potentially resulting in arbitrary behavior.  Many
jaroslav@1258
   799
     *       uses of <code>stop</code> should be replaced by code that simply
jaroslav@1258
   800
     *       modifies some variable to indicate that the target thread should
jaroslav@1258
   801
     *       stop running.  The target thread should check this variable
jaroslav@1258
   802
     *       regularly, and return from its run method in an orderly fashion
jaroslav@1258
   803
     *       if the variable indicates that it is to stop running.  If the
jaroslav@1258
   804
     *       target thread waits for long periods (on a condition variable,
jaroslav@1258
   805
     *       for example), the <code>interrupt</code> method should be used to
jaroslav@1258
   806
     *       interrupt the wait.
jaroslav@1258
   807
     *       For more information, see
jaroslav@1258
   808
     *       <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
jaroslav@1258
   809
     *       are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
jaroslav@1258
   810
     */
jaroslav@1258
   811
    @Deprecated
jaroslav@1258
   812
    public final void stop() {
jaroslav@1258
   813
        stop(new ThreadDeath());
jaroslav@1258
   814
    }
jaroslav@1258
   815
jaroslav@1258
   816
    /**
jaroslav@1258
   817
     * Forces the thread to stop executing.
jaroslav@1258
   818
     * <p>
jaroslav@1258
   819
     * If there is a security manager installed, the <code>checkAccess</code>
jaroslav@1258
   820
     * method of this thread is called, which may result in a
jaroslav@1258
   821
     * <code>SecurityException</code> being raised (in the current thread).
jaroslav@1258
   822
     * <p>
jaroslav@1258
   823
     * If this thread is different from the current thread (that is, the current
jaroslav@1258
   824
     * thread is trying to stop a thread other than itself) or
jaroslav@1258
   825
     * <code>obj</code> is not an instance of <code>ThreadDeath</code>, the
jaroslav@1258
   826
     * security manager's <code>checkPermission</code> method (with the
jaroslav@1258
   827
     * <code>RuntimePermission("stopThread")</code> argument) is called in
jaroslav@1258
   828
     * addition.
jaroslav@1258
   829
     * Again, this may result in throwing a
jaroslav@1258
   830
     * <code>SecurityException</code> (in the current thread).
jaroslav@1258
   831
     * <p>
jaroslav@1258
   832
     * If the argument <code>obj</code> is null, a
jaroslav@1258
   833
     * <code>NullPointerException</code> is thrown (in the current thread).
jaroslav@1258
   834
     * <p>
jaroslav@1258
   835
     * The thread represented by this thread is forced to stop
jaroslav@1258
   836
     * whatever it is doing abnormally and to throw the
jaroslav@1258
   837
     * <code>Throwable</code> object <code>obj</code> as an exception. This
jaroslav@1258
   838
     * is an unusual action to take; normally, the <code>stop</code> method
jaroslav@1258
   839
     * that takes no arguments should be used.
jaroslav@1258
   840
     * <p>
jaroslav@1258
   841
     * It is permitted to stop a thread that has not yet been started.
jaroslav@1258
   842
     * If the thread is eventually started, it immediately terminates.
jaroslav@1258
   843
     *
jaroslav@1258
   844
     * @param      obj   the Throwable object to be thrown.
jaroslav@1258
   845
     * @exception  SecurityException  if the current thread cannot modify
jaroslav@1258
   846
     *               this thread.
jaroslav@1258
   847
     * @throws     NullPointerException if obj is <tt>null</tt>.
jaroslav@1258
   848
     * @see        #interrupt()
jaroslav@1258
   849
     * @see        #checkAccess()
jaroslav@1258
   850
     * @see        #run()
jaroslav@1258
   851
     * @see        #start()
jaroslav@1258
   852
     * @see        #stop()
jaroslav@1258
   853
     * @see        SecurityManager#checkAccess(Thread)
jaroslav@1258
   854
     * @see        SecurityManager#checkPermission
jaroslav@1258
   855
     * @deprecated This method is inherently unsafe.  See {@link #stop()}
jaroslav@1258
   856
     *        for details.  An additional danger of this
jaroslav@1258
   857
     *        method is that it may be used to generate exceptions that the
jaroslav@1258
   858
     *        target thread is unprepared to handle (including checked
jaroslav@1258
   859
     *        exceptions that the thread could not possibly throw, were it
jaroslav@1258
   860
     *        not for this method).
jaroslav@1258
   861
     *        For more information, see
jaroslav@1258
   862
     *        <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
jaroslav@1258
   863
     *        are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
jaroslav@1258
   864
     */
jaroslav@1258
   865
    @Deprecated
jaroslav@1258
   866
    public final synchronized void stop(Throwable obj) {
jaroslav@1258
   867
        if (obj == null)
jaroslav@1258
   868
            throw new NullPointerException();
jaroslav@1258
   869
jaroslav@1258
   870
        SecurityManager security = System.getSecurityManager();
jaroslav@1258
   871
        if (security != null) {
jaroslav@1258
   872
            checkAccess();
jaroslav@1258
   873
            if ((this != Thread.currentThread()) ||
jaroslav@1258
   874
                (!(obj instanceof ThreadDeath))) {
jaroslav@1258
   875
                security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
jaroslav@1258
   876
            }
jaroslav@1258
   877
        }
jaroslav@1258
   878
        // A zero status value corresponds to "NEW", it can't change to
jaroslav@1258
   879
        // not-NEW because we hold the lock.
jaroslav@1258
   880
        if (threadStatus != 0) {
jaroslav@1258
   881
            resume(); // Wake up thread if it was suspended; no-op otherwise
jaroslav@1258
   882
        }
jaroslav@1258
   883
jaroslav@1258
   884
        // The VM can handle all thread states
jaroslav@1258
   885
        stop0(obj);
jaroslav@1258
   886
    }
jaroslav@1258
   887
jaroslav@1258
   888
    /**
jaroslav@1258
   889
     * Interrupts this thread.
jaroslav@1258
   890
     *
jaroslav@1258
   891
     * <p> Unless the current thread is interrupting itself, which is
jaroslav@1258
   892
     * always permitted, the {@link #checkAccess() checkAccess} method
jaroslav@1258
   893
     * of this thread is invoked, which may cause a {@link
jaroslav@1258
   894
     * SecurityException} to be thrown.
jaroslav@1258
   895
     *
jaroslav@1258
   896
     * <p> If this thread is blocked in an invocation of the {@link
jaroslav@1258
   897
     * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
jaroslav@1258
   898
     * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
jaroslav@1258
   899
     * class, or of the {@link #join()}, {@link #join(long)}, {@link
jaroslav@1258
   900
     * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
jaroslav@1258
   901
     * methods of this class, then its interrupt status will be cleared and it
jaroslav@1258
   902
     * will receive an {@link InterruptedException}.
jaroslav@1258
   903
     *
jaroslav@1258
   904
     * <p> If this thread is blocked in an I/O operation upon an {@link
jaroslav@1258
   905
     * java.nio.channels.InterruptibleChannel </code>interruptible
jaroslav@1258
   906
     * channel<code>} then the channel will be closed, the thread's interrupt
jaroslav@1258
   907
     * status will be set, and the thread will receive a {@link
jaroslav@1258
   908
     * java.nio.channels.ClosedByInterruptException}.
jaroslav@1258
   909
     *
jaroslav@1258
   910
     * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
jaroslav@1258
   911
     * then the thread's interrupt status will be set and it will return
jaroslav@1258
   912
     * immediately from the selection operation, possibly with a non-zero
jaroslav@1258
   913
     * value, just as if the selector's {@link
jaroslav@1258
   914
     * java.nio.channels.Selector#wakeup wakeup} method were invoked.
jaroslav@1258
   915
     *
jaroslav@1258
   916
     * <p> If none of the previous conditions hold then this thread's interrupt
jaroslav@1258
   917
     * status will be set. </p>
jaroslav@1258
   918
     *
jaroslav@1258
   919
     * <p> Interrupting a thread that is not alive need not have any effect.
jaroslav@1258
   920
     *
jaroslav@1258
   921
     * @throws  SecurityException
jaroslav@1258
   922
     *          if the current thread cannot modify this thread
jaroslav@1258
   923
     *
jaroslav@1258
   924
     * @revised 6.0
jaroslav@1258
   925
     * @spec JSR-51
jaroslav@1258
   926
     */
jaroslav@1258
   927
    public void interrupt() {
jaroslav@1258
   928
        if (this != Thread.currentThread())
jaroslav@1258
   929
            checkAccess();
jaroslav@1258
   930
jaroslav@1258
   931
        synchronized (blockerLock) {
jaroslav@1258
   932
            Interruptible b = blocker;
jaroslav@1258
   933
            if (b != null) {
jaroslav@1258
   934
                interrupt0();           // Just to set the interrupt flag
jaroslav@1258
   935
                b.interrupt(this);
jaroslav@1258
   936
                return;
jaroslav@1258
   937
            }
jaroslav@1258
   938
        }
jaroslav@1258
   939
        interrupt0();
jaroslav@1258
   940
    }
jaroslav@1258
   941
jaroslav@1258
   942
    /**
jaroslav@1258
   943
     * Tests whether the current thread has been interrupted.  The
jaroslav@1258
   944
     * <i>interrupted status</i> of the thread is cleared by this method.  In
jaroslav@1258
   945
     * other words, if this method were to be called twice in succession, the
jaroslav@1258
   946
     * second call would return false (unless the current thread were
jaroslav@1258
   947
     * interrupted again, after the first call had cleared its interrupted
jaroslav@1258
   948
     * status and before the second call had examined it).
jaroslav@1258
   949
     *
jaroslav@1258
   950
     * <p>A thread interruption ignored because a thread was not alive
jaroslav@1258
   951
     * at the time of the interrupt will be reflected by this method
jaroslav@1258
   952
     * returning false.
jaroslav@1258
   953
     *
jaroslav@1258
   954
     * @return  <code>true</code> if the current thread has been interrupted;
jaroslav@1258
   955
     *          <code>false</code> otherwise.
jaroslav@1258
   956
     * @see #isInterrupted()
jaroslav@1258
   957
     * @revised 6.0
jaroslav@1258
   958
     */
jaroslav@1258
   959
    public static boolean interrupted() {
jaroslav@1258
   960
        return currentThread().isInterrupted(true);
jaroslav@1258
   961
    }
jaroslav@1258
   962
jaroslav@1258
   963
    /**
jaroslav@1258
   964
     * Tests whether this thread has been interrupted.  The <i>interrupted
jaroslav@1258
   965
     * status</i> of the thread is unaffected by this method.
jaroslav@1258
   966
     *
jaroslav@1258
   967
     * <p>A thread interruption ignored because a thread was not alive
jaroslav@1258
   968
     * at the time of the interrupt will be reflected by this method
jaroslav@1258
   969
     * returning false.
jaroslav@1258
   970
     *
jaroslav@1258
   971
     * @return  <code>true</code> if this thread has been interrupted;
jaroslav@1258
   972
     *          <code>false</code> otherwise.
jaroslav@1258
   973
     * @see     #interrupted()
jaroslav@1258
   974
     * @revised 6.0
jaroslav@1258
   975
     */
jaroslav@1258
   976
    public boolean isInterrupted() {
jaroslav@1258
   977
        return isInterrupted(false);
jaroslav@1258
   978
    }
jaroslav@1258
   979
jaroslav@1258
   980
    /**
jaroslav@1258
   981
     * Tests if some Thread has been interrupted.  The interrupted state
jaroslav@1258
   982
     * is reset or not based on the value of ClearInterrupted that is
jaroslav@1258
   983
     * passed.
jaroslav@1258
   984
     */
jaroslav@1258
   985
    private native boolean isInterrupted(boolean ClearInterrupted);
jaroslav@1258
   986
jaroslav@1258
   987
    /**
jaroslav@1258
   988
     * Throws {@link NoSuchMethodError}.
jaroslav@1258
   989
     *
jaroslav@1258
   990
     * @deprecated This method was originally designed to destroy this
jaroslav@1258
   991
     *     thread without any cleanup. Any monitors it held would have
jaroslav@1258
   992
     *     remained locked. However, the method was never implemented.
jaroslav@1258
   993
     *     If if were to be implemented, it would be deadlock-prone in
jaroslav@1258
   994
     *     much the manner of {@link #suspend}. If the target thread held
jaroslav@1258
   995
     *     a lock protecting a critical system resource when it was
jaroslav@1258
   996
     *     destroyed, no thread could ever access this resource again.
jaroslav@1258
   997
     *     If another thread ever attempted to lock this resource, deadlock
jaroslav@1258
   998
     *     would result. Such deadlocks typically manifest themselves as
jaroslav@1258
   999
     *     "frozen" processes. For more information, see
jaroslav@1258
  1000
     *     <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">
jaroslav@1258
  1001
     *     Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
jaroslav@1258
  1002
     * @throws NoSuchMethodError always
jaroslav@1258
  1003
     */
jaroslav@1258
  1004
    @Deprecated
jaroslav@1258
  1005
    public void destroy() {
jaroslav@1258
  1006
        throw new NoSuchMethodError();
jaroslav@1258
  1007
    }
jaroslav@1258
  1008
jaroslav@1258
  1009
    /**
jaroslav@1258
  1010
     * Tests if this thread is alive. A thread is alive if it has
jaroslav@1258
  1011
     * been started and has not yet died.
jaroslav@1258
  1012
     *
jaroslav@1258
  1013
     * @return  <code>true</code> if this thread is alive;
jaroslav@1258
  1014
     *          <code>false</code> otherwise.
jaroslav@1258
  1015
     */
jaroslav@1258
  1016
    public final native boolean isAlive();
jaroslav@1258
  1017
jaroslav@1258
  1018
    /**
jaroslav@1258
  1019
     * Suspends this thread.
jaroslav@1258
  1020
     * <p>
jaroslav@1258
  1021
     * First, the <code>checkAccess</code> method of this thread is called
jaroslav@1258
  1022
     * with no arguments. This may result in throwing a
jaroslav@1258
  1023
     * <code>SecurityException </code>(in the current thread).
jaroslav@1258
  1024
     * <p>
jaroslav@1258
  1025
     * If the thread is alive, it is suspended and makes no further
jaroslav@1258
  1026
     * progress unless and until it is resumed.
jaroslav@1258
  1027
     *
jaroslav@1258
  1028
     * @exception  SecurityException  if the current thread cannot modify
jaroslav@1258
  1029
     *               this thread.
jaroslav@1258
  1030
     * @see #checkAccess
jaroslav@1258
  1031
     * @deprecated   This method has been deprecated, as it is
jaroslav@1258
  1032
     *   inherently deadlock-prone.  If the target thread holds a lock on the
jaroslav@1258
  1033
     *   monitor protecting a critical system resource when it is suspended, no
jaroslav@1258
  1034
     *   thread can access this resource until the target thread is resumed. If
jaroslav@1258
  1035
     *   the thread that would resume the target thread attempts to lock this
jaroslav@1258
  1036
     *   monitor prior to calling <code>resume</code>, deadlock results.  Such
jaroslav@1258
  1037
     *   deadlocks typically manifest themselves as "frozen" processes.
jaroslav@1258
  1038
     *   For more information, see
jaroslav@1258
  1039
     *   <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
jaroslav@1258
  1040
     *   are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
jaroslav@1258
  1041
     */
jaroslav@1258
  1042
    @Deprecated
jaroslav@1258
  1043
    public final void suspend() {
jaroslav@1258
  1044
        checkAccess();
jaroslav@1258
  1045
        suspend0();
jaroslav@1258
  1046
    }
jaroslav@1258
  1047
jaroslav@1258
  1048
    /**
jaroslav@1258
  1049
     * Resumes a suspended thread.
jaroslav@1258
  1050
     * <p>
jaroslav@1258
  1051
     * First, the <code>checkAccess</code> method of this thread is called
jaroslav@1258
  1052
     * with no arguments. This may result in throwing a
jaroslav@1258
  1053
     * <code>SecurityException</code> (in the current thread).
jaroslav@1258
  1054
     * <p>
jaroslav@1258
  1055
     * If the thread is alive but suspended, it is resumed and is
jaroslav@1258
  1056
     * permitted to make progress in its execution.
jaroslav@1258
  1057
     *
jaroslav@1258
  1058
     * @exception  SecurityException  if the current thread cannot modify this
jaroslav@1258
  1059
     *               thread.
jaroslav@1258
  1060
     * @see        #checkAccess
jaroslav@1258
  1061
     * @see        #suspend()
jaroslav@1258
  1062
     * @deprecated This method exists solely for use with {@link #suspend},
jaroslav@1258
  1063
     *     which has been deprecated because it is deadlock-prone.
jaroslav@1258
  1064
     *     For more information, see
jaroslav@1258
  1065
     *     <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
jaroslav@1258
  1066
     *     are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
jaroslav@1258
  1067
     */
jaroslav@1258
  1068
    @Deprecated
jaroslav@1258
  1069
    public final void resume() {
jaroslav@1258
  1070
        checkAccess();
jaroslav@1258
  1071
        resume0();
jaroslav@1258
  1072
    }
jaroslav@1258
  1073
jaroslav@1258
  1074
    /**
jaroslav@1258
  1075
     * Changes the priority of this thread.
jaroslav@1258
  1076
     * <p>
jaroslav@1258
  1077
     * First the <code>checkAccess</code> method of this thread is called
jaroslav@1258
  1078
     * with no arguments. This may result in throwing a
jaroslav@1258
  1079
     * <code>SecurityException</code>.
jaroslav@1258
  1080
     * <p>
jaroslav@1258
  1081
     * Otherwise, the priority of this thread is set to the smaller of
jaroslav@1258
  1082
     * the specified <code>newPriority</code> and the maximum permitted
jaroslav@1258
  1083
     * priority of the thread's thread group.
jaroslav@1258
  1084
     *
jaroslav@1258
  1085
     * @param newPriority priority to set this thread to
jaroslav@1258
  1086
     * @exception  IllegalArgumentException  If the priority is not in the
jaroslav@1258
  1087
     *               range <code>MIN_PRIORITY</code> to
jaroslav@1258
  1088
     *               <code>MAX_PRIORITY</code>.
jaroslav@1258
  1089
     * @exception  SecurityException  if the current thread cannot modify
jaroslav@1258
  1090
     *               this thread.
jaroslav@1258
  1091
     * @see        #getPriority
jaroslav@1258
  1092
     * @see        #checkAccess()
jaroslav@1258
  1093
     * @see        #getThreadGroup()
jaroslav@1258
  1094
     * @see        #MAX_PRIORITY
jaroslav@1258
  1095
     * @see        #MIN_PRIORITY
jaroslav@1258
  1096
     * @see        ThreadGroup#getMaxPriority()
jaroslav@1258
  1097
     */
jaroslav@1258
  1098
    public final void setPriority(int newPriority) {
jaroslav@1258
  1099
        ThreadGroup g;
jaroslav@1258
  1100
        checkAccess();
jaroslav@1258
  1101
        if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
jaroslav@1258
  1102
            throw new IllegalArgumentException();
jaroslav@1258
  1103
        }
jaroslav@1258
  1104
        if((g = getThreadGroup()) != null) {
jaroslav@1258
  1105
            if (newPriority > g.getMaxPriority()) {
jaroslav@1258
  1106
                newPriority = g.getMaxPriority();
jaroslav@1258
  1107
            }
jaroslav@1258
  1108
            setPriority0(priority = newPriority);
jaroslav@1258
  1109
        }
jaroslav@1258
  1110
    }
jaroslav@1258
  1111
jaroslav@1258
  1112
    /**
jaroslav@1258
  1113
     * Returns this thread's priority.
jaroslav@1258
  1114
     *
jaroslav@1258
  1115
     * @return  this thread's priority.
jaroslav@1258
  1116
     * @see     #setPriority
jaroslav@1258
  1117
     */
jaroslav@1258
  1118
    public final int getPriority() {
jaroslav@1258
  1119
        return priority;
jaroslav@1258
  1120
    }
jaroslav@1258
  1121
jaroslav@1258
  1122
    /**
jaroslav@1258
  1123
     * Changes the name of this thread to be equal to the argument
jaroslav@1258
  1124
     * <code>name</code>.
jaroslav@1258
  1125
     * <p>
jaroslav@1258
  1126
     * First the <code>checkAccess</code> method of this thread is called
jaroslav@1258
  1127
     * with no arguments. This may result in throwing a
jaroslav@1258
  1128
     * <code>SecurityException</code>.
jaroslav@1258
  1129
     *
jaroslav@1258
  1130
     * @param      name   the new name for this thread.
jaroslav@1258
  1131
     * @exception  SecurityException  if the current thread cannot modify this
jaroslav@1258
  1132
     *               thread.
jaroslav@1258
  1133
     * @see        #getName
jaroslav@1258
  1134
     * @see        #checkAccess()
jaroslav@1258
  1135
     */
jaroslav@1258
  1136
    public final void setName(String name) {
jaroslav@1258
  1137
        checkAccess();
jaroslav@1258
  1138
        this.name = name.toCharArray();
jaroslav@1258
  1139
    }
jaroslav@1258
  1140
jaroslav@1258
  1141
    /**
jaroslav@1258
  1142
     * Returns this thread's name.
jaroslav@1258
  1143
     *
jaroslav@1258
  1144
     * @return  this thread's name.
jaroslav@1258
  1145
     * @see     #setName(String)
jaroslav@1258
  1146
     */
jaroslav@1258
  1147
    public final String getName() {
jaroslav@1258
  1148
        return String.valueOf(name);
jaroslav@1258
  1149
    }
jaroslav@1258
  1150
jaroslav@1258
  1151
    /**
jaroslav@1258
  1152
     * Returns the thread group to which this thread belongs.
jaroslav@1258
  1153
     * This method returns null if this thread has died
jaroslav@1258
  1154
     * (been stopped).
jaroslav@1258
  1155
     *
jaroslav@1258
  1156
     * @return  this thread's thread group.
jaroslav@1258
  1157
     */
jaroslav@1258
  1158
    public final ThreadGroup getThreadGroup() {
jaroslav@1258
  1159
        return group;
jaroslav@1258
  1160
    }
jaroslav@1258
  1161
jaroslav@1258
  1162
    /**
jaroslav@1258
  1163
     * Returns an estimate of the number of active threads in the current
jaroslav@1258
  1164
     * thread's {@linkplain java.lang.ThreadGroup thread group} and its
jaroslav@1258
  1165
     * subgroups. Recursively iterates over all subgroups in the current
jaroslav@1258
  1166
     * thread's thread group.
jaroslav@1258
  1167
     *
jaroslav@1258
  1168
     * <p> The value returned is only an estimate because the number of
jaroslav@1258
  1169
     * threads may change dynamically while this method traverses internal
jaroslav@1258
  1170
     * data structures, and might be affected by the presence of certain
jaroslav@1258
  1171
     * system threads. This method is intended primarily for debugging
jaroslav@1258
  1172
     * and monitoring purposes.
jaroslav@1258
  1173
     *
jaroslav@1258
  1174
     * @return  an estimate of the number of active threads in the current
jaroslav@1258
  1175
     *          thread's thread group and in any other thread group that
jaroslav@1258
  1176
     *          has the current thread's thread group as an ancestor
jaroslav@1258
  1177
     */
jaroslav@1258
  1178
    public static int activeCount() {
jaroslav@1258
  1179
        return currentThread().getThreadGroup().activeCount();
jaroslav@1258
  1180
    }
jaroslav@1258
  1181
jaroslav@1258
  1182
    /**
jaroslav@1258
  1183
     * Copies into the specified array every active thread in the current
jaroslav@1258
  1184
     * thread's thread group and its subgroups. This method simply
jaroslav@1258
  1185
     * invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])}
jaroslav@1258
  1186
     * method of the current thread's thread group.
jaroslav@1258
  1187
     *
jaroslav@1258
  1188
     * <p> An application might use the {@linkplain #activeCount activeCount}
jaroslav@1258
  1189
     * method to get an estimate of how big the array should be, however
jaroslav@1258
  1190
     * <i>if the array is too short to hold all the threads, the extra threads
jaroslav@1258
  1191
     * are silently ignored.</i>  If it is critical to obtain every active
jaroslav@1258
  1192
     * thread in the current thread's thread group and its subgroups, the
jaroslav@1258
  1193
     * invoker should verify that the returned int value is strictly less
jaroslav@1258
  1194
     * than the length of {@code tarray}.
jaroslav@1258
  1195
     *
jaroslav@1258
  1196
     * <p> Due to the inherent race condition in this method, it is recommended
jaroslav@1258
  1197
     * that the method only be used for debugging and monitoring purposes.
jaroslav@1258
  1198
     *
jaroslav@1258
  1199
     * @param  tarray
jaroslav@1258
  1200
     *         an array into which to put the list of threads
jaroslav@1258
  1201
     *
jaroslav@1258
  1202
     * @return  the number of threads put into the array
jaroslav@1258
  1203
     *
jaroslav@1258
  1204
     * @throws  SecurityException
jaroslav@1258
  1205
     *          if {@link java.lang.ThreadGroup#checkAccess} determines that
jaroslav@1258
  1206
     *          the current thread cannot access its thread group
jaroslav@1258
  1207
     */
jaroslav@1258
  1208
    public static int enumerate(Thread tarray[]) {
jaroslav@1258
  1209
        return currentThread().getThreadGroup().enumerate(tarray);
jaroslav@1258
  1210
    }
jaroslav@1258
  1211
jaroslav@1258
  1212
    /**
jaroslav@1258
  1213
     * Counts the number of stack frames in this thread. The thread must
jaroslav@1258
  1214
     * be suspended.
jaroslav@1258
  1215
     *
jaroslav@1258
  1216
     * @return     the number of stack frames in this thread.
jaroslav@1258
  1217
     * @exception  IllegalThreadStateException  if this thread is not
jaroslav@1258
  1218
     *             suspended.
jaroslav@1258
  1219
     * @deprecated The definition of this call depends on {@link #suspend},
jaroslav@1258
  1220
     *             which is deprecated.  Further, the results of this call
jaroslav@1258
  1221
     *             were never well-defined.
jaroslav@1258
  1222
     */
jaroslav@1258
  1223
    @Deprecated
jaroslav@1258
  1224
    public native int countStackFrames();
jaroslav@1258
  1225
jaroslav@1258
  1226
    /**
jaroslav@1258
  1227
     * Waits at most {@code millis} milliseconds for this thread to
jaroslav@1258
  1228
     * die. A timeout of {@code 0} means to wait forever.
jaroslav@1258
  1229
     *
jaroslav@1258
  1230
     * <p> This implementation uses a loop of {@code this.wait} calls
jaroslav@1258
  1231
     * conditioned on {@code this.isAlive}. As a thread terminates the
jaroslav@1258
  1232
     * {@code this.notifyAll} method is invoked. It is recommended that
jaroslav@1258
  1233
     * applications not use {@code wait}, {@code notify}, or
jaroslav@1258
  1234
     * {@code notifyAll} on {@code Thread} instances.
jaroslav@1258
  1235
     *
jaroslav@1258
  1236
     * @param  millis
jaroslav@1258
  1237
     *         the time to wait in milliseconds
jaroslav@1258
  1238
     *
jaroslav@1258
  1239
     * @throws  IllegalArgumentException
jaroslav@1258
  1240
     *          if the value of {@code millis} is negative
jaroslav@1258
  1241
     *
jaroslav@1258
  1242
     * @throws  InterruptedException
jaroslav@1258
  1243
     *          if any thread has interrupted the current thread. The
jaroslav@1258
  1244
     *          <i>interrupted status</i> of the current thread is
jaroslav@1258
  1245
     *          cleared when this exception is thrown.
jaroslav@1258
  1246
     */
jaroslav@1258
  1247
    public final synchronized void join(long millis)
jaroslav@1258
  1248
    throws InterruptedException {
jaroslav@1258
  1249
        long base = System.currentTimeMillis();
jaroslav@1258
  1250
        long now = 0;
jaroslav@1258
  1251
jaroslav@1258
  1252
        if (millis < 0) {
jaroslav@1258
  1253
            throw new IllegalArgumentException("timeout value is negative");
jaroslav@1258
  1254
        }
jaroslav@1258
  1255
jaroslav@1258
  1256
        if (millis == 0) {
jaroslav@1258
  1257
            while (isAlive()) {
jaroslav@1258
  1258
                wait(0);
jaroslav@1258
  1259
            }
jaroslav@1258
  1260
        } else {
jaroslav@1258
  1261
            while (isAlive()) {
jaroslav@1258
  1262
                long delay = millis - now;
jaroslav@1258
  1263
                if (delay <= 0) {
jaroslav@1258
  1264
                    break;
jaroslav@1258
  1265
                }
jaroslav@1258
  1266
                wait(delay);
jaroslav@1258
  1267
                now = System.currentTimeMillis() - base;
jaroslav@1258
  1268
            }
jaroslav@1258
  1269
        }
jaroslav@1258
  1270
    }
jaroslav@1258
  1271
jaroslav@1258
  1272
    /**
jaroslav@1258
  1273
     * Waits at most {@code millis} milliseconds plus
jaroslav@1258
  1274
     * {@code nanos} nanoseconds for this thread to die.
jaroslav@1258
  1275
     *
jaroslav@1258
  1276
     * <p> This implementation uses a loop of {@code this.wait} calls
jaroslav@1258
  1277
     * conditioned on {@code this.isAlive}. As a thread terminates the
jaroslav@1258
  1278
     * {@code this.notifyAll} method is invoked. It is recommended that
jaroslav@1258
  1279
     * applications not use {@code wait}, {@code notify}, or
jaroslav@1258
  1280
     * {@code notifyAll} on {@code Thread} instances.
jaroslav@1258
  1281
     *
jaroslav@1258
  1282
     * @param  millis
jaroslav@1258
  1283
     *         the time to wait in milliseconds
jaroslav@1258
  1284
     *
jaroslav@1258
  1285
     * @param  nanos
jaroslav@1258
  1286
     *         {@code 0-999999} additional nanoseconds to wait
jaroslav@1258
  1287
     *
jaroslav@1258
  1288
     * @throws  IllegalArgumentException
jaroslav@1258
  1289
     *          if the value of {@code millis} is negative, or the value
jaroslav@1258
  1290
     *          of {@code nanos} is not in the range {@code 0-999999}
jaroslav@1258
  1291
     *
jaroslav@1258
  1292
     * @throws  InterruptedException
jaroslav@1258
  1293
     *          if any thread has interrupted the current thread. The
jaroslav@1258
  1294
     *          <i>interrupted status</i> of the current thread is
jaroslav@1258
  1295
     *          cleared when this exception is thrown.
jaroslav@1258
  1296
     */
jaroslav@1258
  1297
    public final synchronized void join(long millis, int nanos)
jaroslav@1258
  1298
    throws InterruptedException {
jaroslav@1258
  1299
jaroslav@1258
  1300
        if (millis < 0) {
jaroslav@1258
  1301
            throw new IllegalArgumentException("timeout value is negative");
jaroslav@1258
  1302
        }
jaroslav@1258
  1303
jaroslav@1258
  1304
        if (nanos < 0 || nanos > 999999) {
jaroslav@1258
  1305
            throw new IllegalArgumentException(
jaroslav@1258
  1306
                                "nanosecond timeout value out of range");
jaroslav@1258
  1307
        }
jaroslav@1258
  1308
jaroslav@1258
  1309
        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
jaroslav@1258
  1310
            millis++;
jaroslav@1258
  1311
        }
jaroslav@1258
  1312
jaroslav@1258
  1313
        join(millis);
jaroslav@1258
  1314
    }
jaroslav@1258
  1315
jaroslav@1258
  1316
    /**
jaroslav@1258
  1317
     * Waits for this thread to die.
jaroslav@1258
  1318
     *
jaroslav@1258
  1319
     * <p> An invocation of this method behaves in exactly the same
jaroslav@1258
  1320
     * way as the invocation
jaroslav@1258
  1321
     *
jaroslav@1258
  1322
     * <blockquote>
jaroslav@1258
  1323
     * {@linkplain #join(long) join}{@code (0)}
jaroslav@1258
  1324
     * </blockquote>
jaroslav@1258
  1325
     *
jaroslav@1258
  1326
     * @throws  InterruptedException
jaroslav@1258
  1327
     *          if any thread has interrupted the current thread. The
jaroslav@1258
  1328
     *          <i>interrupted status</i> of the current thread is
jaroslav@1258
  1329
     *          cleared when this exception is thrown.
jaroslav@1258
  1330
     */
jaroslav@1258
  1331
    public final void join() throws InterruptedException {
jaroslav@1258
  1332
        join(0);
jaroslav@1258
  1333
    }
jaroslav@1258
  1334
jaroslav@1258
  1335
    /**
jaroslav@1258
  1336
     * Prints a stack trace of the current thread to the standard error stream.
jaroslav@1258
  1337
     * This method is used only for debugging.
jaroslav@1258
  1338
     *
jaroslav@1258
  1339
     * @see     Throwable#printStackTrace()
jaroslav@1258
  1340
     */
jaroslav@1258
  1341
    public static void dumpStack() {
jaroslav@1258
  1342
        new Exception("Stack trace").printStackTrace();
jaroslav@1258
  1343
    }
jaroslav@1258
  1344
jaroslav@1258
  1345
    /**
jaroslav@1258
  1346
     * Marks this thread as either a {@linkplain #isDaemon daemon} thread
jaroslav@1258
  1347
     * or a user thread. The Java Virtual Machine exits when the only
jaroslav@1258
  1348
     * threads running are all daemon threads.
jaroslav@1258
  1349
     *
jaroslav@1258
  1350
     * <p> This method must be invoked before the thread is started.
jaroslav@1258
  1351
     *
jaroslav@1258
  1352
     * @param  on
jaroslav@1258
  1353
     *         if {@code true}, marks this thread as a daemon thread
jaroslav@1258
  1354
     *
jaroslav@1258
  1355
     * @throws  IllegalThreadStateException
jaroslav@1258
  1356
     *          if this thread is {@linkplain #isAlive alive}
jaroslav@1258
  1357
     *
jaroslav@1258
  1358
     * @throws  SecurityException
jaroslav@1258
  1359
     *          if {@link #checkAccess} determines that the current
jaroslav@1258
  1360
     *          thread cannot modify this thread
jaroslav@1258
  1361
     */
jaroslav@1258
  1362
    public final void setDaemon(boolean on) {
jaroslav@1258
  1363
        checkAccess();
jaroslav@1258
  1364
        if (isAlive()) {
jaroslav@1258
  1365
            throw new IllegalThreadStateException();
jaroslav@1258
  1366
        }
jaroslav@1258
  1367
        daemon = on;
jaroslav@1258
  1368
    }
jaroslav@1258
  1369
jaroslav@1258
  1370
    /**
jaroslav@1258
  1371
     * Tests if this thread is a daemon thread.
jaroslav@1258
  1372
     *
jaroslav@1258
  1373
     * @return  <code>true</code> if this thread is a daemon thread;
jaroslav@1258
  1374
     *          <code>false</code> otherwise.
jaroslav@1258
  1375
     * @see     #setDaemon(boolean)
jaroslav@1258
  1376
     */
jaroslav@1258
  1377
    public final boolean isDaemon() {
jaroslav@1258
  1378
        return daemon;
jaroslav@1258
  1379
    }
jaroslav@1258
  1380
jaroslav@1258
  1381
    /**
jaroslav@1258
  1382
     * Determines if the currently running thread has permission to
jaroslav@1258
  1383
     * modify this thread.
jaroslav@1258
  1384
     * <p>
jaroslav@1258
  1385
     * If there is a security manager, its <code>checkAccess</code> method
jaroslav@1258
  1386
     * is called with this thread as its argument. This may result in
jaroslav@1258
  1387
     * throwing a <code>SecurityException</code>.
jaroslav@1258
  1388
     *
jaroslav@1258
  1389
     * @exception  SecurityException  if the current thread is not allowed to
jaroslav@1258
  1390
     *               access this thread.
jaroslav@1258
  1391
     * @see        SecurityManager#checkAccess(Thread)
jaroslav@1258
  1392
     */
jaroslav@1258
  1393
    public final void checkAccess() {
jaroslav@1258
  1394
        SecurityManager security = System.getSecurityManager();
jaroslav@1258
  1395
        if (security != null) {
jaroslav@1258
  1396
            security.checkAccess(this);
jaroslav@1258
  1397
        }
jaroslav@1258
  1398
    }
jaroslav@1258
  1399
jaroslav@1258
  1400
    /**
jaroslav@1258
  1401
     * Returns a string representation of this thread, including the
jaroslav@1258
  1402
     * thread's name, priority, and thread group.
jaroslav@1258
  1403
     *
jaroslav@1258
  1404
     * @return  a string representation of this thread.
jaroslav@1258
  1405
     */
jaroslav@1258
  1406
    public String toString() {
jaroslav@1258
  1407
        ThreadGroup group = getThreadGroup();
jaroslav@1258
  1408
        if (group != null) {
jaroslav@1258
  1409
            return "Thread[" + getName() + "," + getPriority() + "," +
jaroslav@1258
  1410
                           group.getName() + "]";
jaroslav@1258
  1411
        } else {
jaroslav@1258
  1412
            return "Thread[" + getName() + "," + getPriority() + "," +
jaroslav@1258
  1413
                            "" + "]";
jaroslav@1258
  1414
        }
jaroslav@1258
  1415
    }
jaroslav@1258
  1416
jaroslav@1258
  1417
    /**
jaroslav@1258
  1418
     * Returns the context ClassLoader for this Thread. The context
jaroslav@1258
  1419
     * ClassLoader is provided by the creator of the thread for use
jaroslav@1258
  1420
     * by code running in this thread when loading classes and resources.
jaroslav@1258
  1421
     * If not {@linkplain #setContextClassLoader set}, the default is the
jaroslav@1258
  1422
     * ClassLoader context of the parent Thread. The context ClassLoader of the
jaroslav@1258
  1423
     * primordial thread is typically set to the class loader used to load the
jaroslav@1258
  1424
     * application.
jaroslav@1258
  1425
     *
jaroslav@1258
  1426
     * <p>If a security manager is present, and the invoker's class loader is not
jaroslav@1258
  1427
     * {@code null} and is not the same as or an ancestor of the context class
jaroslav@1258
  1428
     * loader, then this method invokes the security manager's {@link
jaroslav@1258
  1429
     * SecurityManager#checkPermission(java.security.Permission) checkPermission}
jaroslav@1258
  1430
     * method with a {@link RuntimePermission RuntimePermission}{@code
jaroslav@1258
  1431
     * ("getClassLoader")} permission to verify that retrieval of the context
jaroslav@1258
  1432
     * class loader is permitted.
jaroslav@1258
  1433
     *
jaroslav@1258
  1434
     * @return  the context ClassLoader for this Thread, or {@code null}
jaroslav@1258
  1435
     *          indicating the system class loader (or, failing that, the
jaroslav@1258
  1436
     *          bootstrap class loader)
jaroslav@1258
  1437
     *
jaroslav@1258
  1438
     * @throws  SecurityException
jaroslav@1258
  1439
     *          if the current thread cannot get the context ClassLoader
jaroslav@1258
  1440
     *
jaroslav@1258
  1441
     * @since 1.2
jaroslav@1258
  1442
     */
jaroslav@1258
  1443
    public ClassLoader getContextClassLoader() {
jaroslav@1258
  1444
        if (contextClassLoader == null)
jaroslav@1258
  1445
            return null;
jaroslav@1258
  1446
        SecurityManager sm = System.getSecurityManager();
jaroslav@1258
  1447
        if (sm != null) {
jaroslav@1258
  1448
            ClassLoader ccl = ClassLoader.getCallerClassLoader();
jaroslav@1258
  1449
            if (ccl != null && ccl != contextClassLoader &&
jaroslav@1258
  1450
                    !contextClassLoader.isAncestor(ccl)) {
jaroslav@1258
  1451
                sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
jaroslav@1258
  1452
            }
jaroslav@1258
  1453
        }
jaroslav@1258
  1454
        return contextClassLoader;
jaroslav@1258
  1455
    }
jaroslav@1258
  1456
jaroslav@1258
  1457
    /**
jaroslav@1258
  1458
     * Sets the context ClassLoader for this Thread. The context
jaroslav@1258
  1459
     * ClassLoader can be set when a thread is created, and allows
jaroslav@1258
  1460
     * the creator of the thread to provide the appropriate class loader,
jaroslav@1258
  1461
     * through {@code getContextClassLoader}, to code running in the thread
jaroslav@1258
  1462
     * when loading classes and resources.
jaroslav@1258
  1463
     *
jaroslav@1258
  1464
     * <p>If a security manager is present, its {@link
jaroslav@1258
  1465
     * SecurityManager#checkPermission(java.security.Permission) checkPermission}
jaroslav@1258
  1466
     * method is invoked with a {@link RuntimePermission RuntimePermission}{@code
jaroslav@1258
  1467
     * ("setContextClassLoader")} permission to see if setting the context
jaroslav@1258
  1468
     * ClassLoader is permitted.
jaroslav@1258
  1469
     *
jaroslav@1258
  1470
     * @param  cl
jaroslav@1258
  1471
     *         the context ClassLoader for this Thread, or null  indicating the
jaroslav@1258
  1472
     *         system class loader (or, failing that, the bootstrap class loader)
jaroslav@1258
  1473
     *
jaroslav@1258
  1474
     * @throws  SecurityException
jaroslav@1258
  1475
     *          if the current thread cannot set the context ClassLoader
jaroslav@1258
  1476
     *
jaroslav@1258
  1477
     * @since 1.2
jaroslav@1258
  1478
     */
jaroslav@1258
  1479
    public void setContextClassLoader(ClassLoader cl) {
jaroslav@1258
  1480
        SecurityManager sm = System.getSecurityManager();
jaroslav@1258
  1481
        if (sm != null) {
jaroslav@1258
  1482
            sm.checkPermission(new RuntimePermission("setContextClassLoader"));
jaroslav@1258
  1483
        }
jaroslav@1258
  1484
        contextClassLoader = cl;
jaroslav@1258
  1485
    }
jaroslav@1258
  1486
jaroslav@1258
  1487
    /**
jaroslav@1258
  1488
     * Returns <tt>true</tt> if and only if the current thread holds the
jaroslav@1258
  1489
     * monitor lock on the specified object.
jaroslav@1258
  1490
     *
jaroslav@1258
  1491
     * <p>This method is designed to allow a program to assert that
jaroslav@1258
  1492
     * the current thread already holds a specified lock:
jaroslav@1258
  1493
     * <pre>
jaroslav@1258
  1494
     *     assert Thread.holdsLock(obj);
jaroslav@1258
  1495
     * </pre>
jaroslav@1258
  1496
     *
jaroslav@1258
  1497
     * @param  obj the object on which to test lock ownership
jaroslav@1258
  1498
     * @throws NullPointerException if obj is <tt>null</tt>
jaroslav@1258
  1499
     * @return <tt>true</tt> if the current thread holds the monitor lock on
jaroslav@1258
  1500
     *         the specified object.
jaroslav@1258
  1501
     * @since 1.4
jaroslav@1258
  1502
     */
jaroslav@1258
  1503
    public static native boolean holdsLock(Object obj);
jaroslav@1258
  1504
jaroslav@1258
  1505
    private static final StackTraceElement[] EMPTY_STACK_TRACE
jaroslav@1258
  1506
        = new StackTraceElement[0];
jaroslav@1258
  1507
jaroslav@1258
  1508
    /**
jaroslav@1258
  1509
     * Returns an array of stack trace elements representing the stack dump
jaroslav@1258
  1510
     * of this thread.  This method will return a zero-length array if
jaroslav@1258
  1511
     * this thread has not started, has started but has not yet been
jaroslav@1258
  1512
     * scheduled to run by the system, or has terminated.
jaroslav@1258
  1513
     * If the returned array is of non-zero length then the first element of
jaroslav@1258
  1514
     * the array represents the top of the stack, which is the most recent
jaroslav@1258
  1515
     * method invocation in the sequence.  The last element of the array
jaroslav@1258
  1516
     * represents the bottom of the stack, which is the least recent method
jaroslav@1258
  1517
     * invocation in the sequence.
jaroslav@1258
  1518
     *
jaroslav@1258
  1519
     * <p>If there is a security manager, and this thread is not
jaroslav@1258
  1520
     * the current thread, then the security manager's
jaroslav@1258
  1521
     * <tt>checkPermission</tt> method is called with a
jaroslav@1258
  1522
     * <tt>RuntimePermission("getStackTrace")</tt> permission
jaroslav@1258
  1523
     * to see if it's ok to get the stack trace.
jaroslav@1258
  1524
     *
jaroslav@1258
  1525
     * <p>Some virtual machines may, under some circumstances, omit one
jaroslav@1258
  1526
     * or more stack frames from the stack trace.  In the extreme case,
jaroslav@1258
  1527
     * a virtual machine that has no stack trace information concerning
jaroslav@1258
  1528
     * this thread is permitted to return a zero-length array from this
jaroslav@1258
  1529
     * method.
jaroslav@1258
  1530
     *
jaroslav@1258
  1531
     * @return an array of <tt>StackTraceElement</tt>,
jaroslav@1258
  1532
     * each represents one stack frame.
jaroslav@1258
  1533
     *
jaroslav@1258
  1534
     * @throws SecurityException
jaroslav@1258
  1535
     *        if a security manager exists and its
jaroslav@1258
  1536
     *        <tt>checkPermission</tt> method doesn't allow
jaroslav@1258
  1537
     *        getting the stack trace of thread.
jaroslav@1258
  1538
     * @see SecurityManager#checkPermission
jaroslav@1258
  1539
     * @see RuntimePermission
jaroslav@1258
  1540
     * @see Throwable#getStackTrace
jaroslav@1258
  1541
     *
jaroslav@1258
  1542
     * @since 1.5
jaroslav@1258
  1543
     */
jaroslav@1258
  1544
    public StackTraceElement[] getStackTrace() {
jaroslav@1258
  1545
        if (this != Thread.currentThread()) {
jaroslav@1258
  1546
            // check for getStackTrace permission
jaroslav@1258
  1547
            SecurityManager security = System.getSecurityManager();
jaroslav@1258
  1548
            if (security != null) {
jaroslav@1258
  1549
                security.checkPermission(
jaroslav@1258
  1550
                    SecurityConstants.GET_STACK_TRACE_PERMISSION);
jaroslav@1258
  1551
            }
jaroslav@1258
  1552
            // optimization so we do not call into the vm for threads that
jaroslav@1258
  1553
            // have not yet started or have terminated
jaroslav@1258
  1554
            if (!isAlive()) {
jaroslav@1258
  1555
                return EMPTY_STACK_TRACE;
jaroslav@1258
  1556
            }
jaroslav@1258
  1557
            StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this});
jaroslav@1258
  1558
            StackTraceElement[] stackTrace = stackTraceArray[0];
jaroslav@1258
  1559
            // a thread that was alive during the previous isAlive call may have
jaroslav@1258
  1560
            // since terminated, therefore not having a stacktrace.
jaroslav@1258
  1561
            if (stackTrace == null) {
jaroslav@1258
  1562
                stackTrace = EMPTY_STACK_TRACE;
jaroslav@1258
  1563
            }
jaroslav@1258
  1564
            return stackTrace;
jaroslav@1258
  1565
        } else {
jaroslav@1258
  1566
            // Don't need JVM help for current thread
jaroslav@1258
  1567
            return (new Exception()).getStackTrace();
jaroslav@1258
  1568
        }
jaroslav@1258
  1569
    }
jaroslav@1258
  1570
jaroslav@1258
  1571
    /**
jaroslav@1258
  1572
     * Returns a map of stack traces for all live threads.
jaroslav@1258
  1573
     * The map keys are threads and each map value is an array of
jaroslav@1258
  1574
     * <tt>StackTraceElement</tt> that represents the stack dump
jaroslav@1258
  1575
     * of the corresponding <tt>Thread</tt>.
jaroslav@1258
  1576
     * The returned stack traces are in the format specified for
jaroslav@1258
  1577
     * the {@link #getStackTrace getStackTrace} method.
jaroslav@1258
  1578
     *
jaroslav@1258
  1579
     * <p>The threads may be executing while this method is called.
jaroslav@1258
  1580
     * The stack trace of each thread only represents a snapshot and
jaroslav@1258
  1581
     * each stack trace may be obtained at different time.  A zero-length
jaroslav@1258
  1582
     * array will be returned in the map value if the virtual machine has
jaroslav@1258
  1583
     * no stack trace information about a thread.
jaroslav@1258
  1584
     *
jaroslav@1258
  1585
     * <p>If there is a security manager, then the security manager's
jaroslav@1258
  1586
     * <tt>checkPermission</tt> method is called with a
jaroslav@1258
  1587
     * <tt>RuntimePermission("getStackTrace")</tt> permission as well as
jaroslav@1258
  1588
     * <tt>RuntimePermission("modifyThreadGroup")</tt> permission
jaroslav@1258
  1589
     * to see if it is ok to get the stack trace of all threads.
jaroslav@1258
  1590
     *
jaroslav@1258
  1591
     * @return a <tt>Map</tt> from <tt>Thread</tt> to an array of
jaroslav@1258
  1592
     * <tt>StackTraceElement</tt> that represents the stack trace of
jaroslav@1258
  1593
     * the corresponding thread.
jaroslav@1258
  1594
     *
jaroslav@1258
  1595
     * @throws SecurityException
jaroslav@1258
  1596
     *        if a security manager exists and its
jaroslav@1258
  1597
     *        <tt>checkPermission</tt> method doesn't allow
jaroslav@1258
  1598
     *        getting the stack trace of thread.
jaroslav@1258
  1599
     * @see #getStackTrace
jaroslav@1258
  1600
     * @see SecurityManager#checkPermission
jaroslav@1258
  1601
     * @see RuntimePermission
jaroslav@1258
  1602
     * @see Throwable#getStackTrace
jaroslav@1258
  1603
     *
jaroslav@1258
  1604
     * @since 1.5
jaroslav@1258
  1605
     */
jaroslav@1258
  1606
    public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
jaroslav@1258
  1607
        // check for getStackTrace permission
jaroslav@1258
  1608
        SecurityManager security = System.getSecurityManager();
jaroslav@1258
  1609
        if (security != null) {
jaroslav@1258
  1610
            security.checkPermission(
jaroslav@1258
  1611
                SecurityConstants.GET_STACK_TRACE_PERMISSION);
jaroslav@1258
  1612
            security.checkPermission(
jaroslav@1258
  1613
                SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
jaroslav@1258
  1614
        }
jaroslav@1258
  1615
jaroslav@1258
  1616
        // Get a snapshot of the list of all threads
jaroslav@1258
  1617
        Thread[] threads = getThreads();
jaroslav@1258
  1618
        StackTraceElement[][] traces = dumpThreads(threads);
jaroslav@1258
  1619
        Map<Thread, StackTraceElement[]> m = new HashMap<>(threads.length);
jaroslav@1258
  1620
        for (int i = 0; i < threads.length; i++) {
jaroslav@1258
  1621
            StackTraceElement[] stackTrace = traces[i];
jaroslav@1258
  1622
            if (stackTrace != null) {
jaroslav@1258
  1623
                m.put(threads[i], stackTrace);
jaroslav@1258
  1624
            }
jaroslav@1258
  1625
            // else terminated so we don't put it in the map
jaroslav@1258
  1626
        }
jaroslav@1258
  1627
        return m;
jaroslav@1258
  1628
    }
jaroslav@1258
  1629
jaroslav@1258
  1630
jaroslav@1258
  1631
    private static final RuntimePermission SUBCLASS_IMPLEMENTATION_PERMISSION =
jaroslav@1258
  1632
                    new RuntimePermission("enableContextClassLoaderOverride");
jaroslav@1258
  1633
jaroslav@1258
  1634
    /** cache of subclass security audit results */
jaroslav@1258
  1635
    /* Replace with ConcurrentReferenceHashMap when/if it appears in a future
jaroslav@1258
  1636
     * release */
jaroslav@1258
  1637
    private static class Caches {
jaroslav@1258
  1638
        /** cache of subclass security audit results */
jaroslav@1258
  1639
        static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
jaroslav@1258
  1640
            new ConcurrentHashMap<>();
jaroslav@1258
  1641
jaroslav@1258
  1642
        /** queue for WeakReferences to audited subclasses */
jaroslav@1258
  1643
        static final ReferenceQueue<Class<?>> subclassAuditsQueue =
jaroslav@1258
  1644
            new ReferenceQueue<>();
jaroslav@1258
  1645
    }
jaroslav@1258
  1646
jaroslav@1258
  1647
    /**
jaroslav@1258
  1648
     * Verifies that this (possibly subclass) instance can be constructed
jaroslav@1258
  1649
     * without violating security constraints: the subclass must not override
jaroslav@1258
  1650
     * security-sensitive non-final methods, or else the
jaroslav@1258
  1651
     * "enableContextClassLoaderOverride" RuntimePermission is checked.
jaroslav@1258
  1652
     */
jaroslav@1258
  1653
    private static boolean isCCLOverridden(Class cl) {
jaroslav@1258
  1654
        if (cl == Thread.class)
jaroslav@1258
  1655
            return false;
jaroslav@1258
  1656
jaroslav@1258
  1657
        processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
jaroslav@1258
  1658
        WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
jaroslav@1258
  1659
        Boolean result = Caches.subclassAudits.get(key);
jaroslav@1258
  1660
        if (result == null) {
jaroslav@1258
  1661
            result = Boolean.valueOf(auditSubclass(cl));
jaroslav@1258
  1662
            Caches.subclassAudits.putIfAbsent(key, result);
jaroslav@1258
  1663
        }
jaroslav@1258
  1664
jaroslav@1258
  1665
        return result.booleanValue();
jaroslav@1258
  1666
    }
jaroslav@1258
  1667
jaroslav@1258
  1668
    /**
jaroslav@1258
  1669
     * Performs reflective checks on given subclass to verify that it doesn't
jaroslav@1258
  1670
     * override security-sensitive non-final methods.  Returns true if the
jaroslav@1258
  1671
     * subclass overrides any of the methods, false otherwise.
jaroslav@1258
  1672
     */
jaroslav@1258
  1673
    private static boolean auditSubclass(final Class subcl) {
jaroslav@1258
  1674
        Boolean result = AccessController.doPrivileged(
jaroslav@1258
  1675
            new PrivilegedAction<Boolean>() {
jaroslav@1258
  1676
                public Boolean run() {
jaroslav@1258
  1677
                    for (Class cl = subcl;
jaroslav@1258
  1678
                         cl != Thread.class;
jaroslav@1258
  1679
                         cl = cl.getSuperclass())
jaroslav@1258
  1680
                    {
jaroslav@1258
  1681
                        try {
jaroslav@1258
  1682
                            cl.getDeclaredMethod("getContextClassLoader", new Class[0]);
jaroslav@1258
  1683
                            return Boolean.TRUE;
jaroslav@1258
  1684
                        } catch (NoSuchMethodException ex) {
jaroslav@1258
  1685
                        }
jaroslav@1258
  1686
                        try {
jaroslav@1258
  1687
                            Class[] params = {ClassLoader.class};
jaroslav@1258
  1688
                            cl.getDeclaredMethod("setContextClassLoader", params);
jaroslav@1258
  1689
                            return Boolean.TRUE;
jaroslav@1258
  1690
                        } catch (NoSuchMethodException ex) {
jaroslav@1258
  1691
                        }
jaroslav@1258
  1692
                    }
jaroslav@1258
  1693
                    return Boolean.FALSE;
jaroslav@1258
  1694
                }
jaroslav@1258
  1695
            }
jaroslav@1258
  1696
        );
jaroslav@1258
  1697
        return result.booleanValue();
jaroslav@1258
  1698
    }
jaroslav@1258
  1699
jaroslav@1258
  1700
    private native static StackTraceElement[][] dumpThreads(Thread[] threads);
jaroslav@1258
  1701
    private native static Thread[] getThreads();
jaroslav@1258
  1702
jaroslav@1258
  1703
    /**
jaroslav@1258
  1704
     * Returns the identifier of this Thread.  The thread ID is a positive
jaroslav@1258
  1705
     * <tt>long</tt> number generated when this thread was created.
jaroslav@1258
  1706
     * The thread ID is unique and remains unchanged during its lifetime.
jaroslav@1258
  1707
     * When a thread is terminated, this thread ID may be reused.
jaroslav@1258
  1708
     *
jaroslav@1258
  1709
     * @return this thread's ID.
jaroslav@1258
  1710
     * @since 1.5
jaroslav@1258
  1711
     */
jaroslav@1258
  1712
    public long getId() {
jaroslav@1258
  1713
        return tid;
jaroslav@1258
  1714
    }
jaroslav@1258
  1715
jaroslav@1258
  1716
    /**
jaroslav@1258
  1717
     * A thread state.  A thread can be in one of the following states:
jaroslav@1258
  1718
     * <ul>
jaroslav@1258
  1719
     * <li>{@link #NEW}<br>
jaroslav@1258
  1720
     *     A thread that has not yet started is in this state.
jaroslav@1258
  1721
     *     </li>
jaroslav@1258
  1722
     * <li>{@link #RUNNABLE}<br>
jaroslav@1258
  1723
     *     A thread executing in the Java virtual machine is in this state.
jaroslav@1258
  1724
     *     </li>
jaroslav@1258
  1725
     * <li>{@link #BLOCKED}<br>
jaroslav@1258
  1726
     *     A thread that is blocked waiting for a monitor lock
jaroslav@1258
  1727
     *     is in this state.
jaroslav@1258
  1728
     *     </li>
jaroslav@1258
  1729
     * <li>{@link #WAITING}<br>
jaroslav@1258
  1730
     *     A thread that is waiting indefinitely for another thread to
jaroslav@1258
  1731
     *     perform a particular action is in this state.
jaroslav@1258
  1732
     *     </li>
jaroslav@1258
  1733
     * <li>{@link #TIMED_WAITING}<br>
jaroslav@1258
  1734
     *     A thread that is waiting for another thread to perform an action
jaroslav@1258
  1735
     *     for up to a specified waiting time is in this state.
jaroslav@1258
  1736
     *     </li>
jaroslav@1258
  1737
     * <li>{@link #TERMINATED}<br>
jaroslav@1258
  1738
     *     A thread that has exited is in this state.
jaroslav@1258
  1739
     *     </li>
jaroslav@1258
  1740
     * </ul>
jaroslav@1258
  1741
     *
jaroslav@1258
  1742
     * <p>
jaroslav@1258
  1743
     * A thread can be in only one state at a given point in time.
jaroslav@1258
  1744
     * These states are virtual machine states which do not reflect
jaroslav@1258
  1745
     * any operating system thread states.
jaroslav@1258
  1746
     *
jaroslav@1258
  1747
     * @since   1.5
jaroslav@1258
  1748
     * @see #getState
jaroslav@1258
  1749
     */
jaroslav@1258
  1750
    public enum State {
jaroslav@1258
  1751
        /**
jaroslav@1258
  1752
         * Thread state for a thread which has not yet started.
jaroslav@1258
  1753
         */
jaroslav@1258
  1754
        NEW,
jaroslav@1258
  1755
jaroslav@1258
  1756
        /**
jaroslav@1258
  1757
         * Thread state for a runnable thread.  A thread in the runnable
jaroslav@1258
  1758
         * state is executing in the Java virtual machine but it may
jaroslav@1258
  1759
         * be waiting for other resources from the operating system
jaroslav@1258
  1760
         * such as processor.
jaroslav@1258
  1761
         */
jaroslav@1258
  1762
        RUNNABLE,
jaroslav@1258
  1763
jaroslav@1258
  1764
        /**
jaroslav@1258
  1765
         * Thread state for a thread blocked waiting for a monitor lock.
jaroslav@1258
  1766
         * A thread in the blocked state is waiting for a monitor lock
jaroslav@1258
  1767
         * to enter a synchronized block/method or
jaroslav@1258
  1768
         * reenter a synchronized block/method after calling
jaroslav@1258
  1769
         * {@link Object#wait() Object.wait}.
jaroslav@1258
  1770
         */
jaroslav@1258
  1771
        BLOCKED,
jaroslav@1258
  1772
jaroslav@1258
  1773
        /**
jaroslav@1258
  1774
         * Thread state for a waiting thread.
jaroslav@1258
  1775
         * A thread is in the waiting state due to calling one of the
jaroslav@1258
  1776
         * following methods:
jaroslav@1258
  1777
         * <ul>
jaroslav@1258
  1778
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
jaroslav@1258
  1779
         *   <li>{@link #join() Thread.join} with no timeout</li>
jaroslav@1258
  1780
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
jaroslav@1258
  1781
         * </ul>
jaroslav@1258
  1782
         *
jaroslav@1258
  1783
         * <p>A thread in the waiting state is waiting for another thread to
jaroslav@1258
  1784
         * perform a particular action.
jaroslav@1258
  1785
         *
jaroslav@1258
  1786
         * For example, a thread that has called <tt>Object.wait()</tt>
jaroslav@1258
  1787
         * on an object is waiting for another thread to call
jaroslav@1258
  1788
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
jaroslav@1258
  1789
         * that object. A thread that has called <tt>Thread.join()</tt>
jaroslav@1258
  1790
         * is waiting for a specified thread to terminate.
jaroslav@1258
  1791
         */
jaroslav@1258
  1792
        WAITING,
jaroslav@1258
  1793
jaroslav@1258
  1794
        /**
jaroslav@1258
  1795
         * Thread state for a waiting thread with a specified waiting time.
jaroslav@1258
  1796
         * A thread is in the timed waiting state due to calling one of
jaroslav@1258
  1797
         * the following methods with a specified positive waiting time:
jaroslav@1258
  1798
         * <ul>
jaroslav@1258
  1799
         *   <li>{@link #sleep Thread.sleep}</li>
jaroslav@1258
  1800
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
jaroslav@1258
  1801
         *   <li>{@link #join(long) Thread.join} with timeout</li>
jaroslav@1258
  1802
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
jaroslav@1258
  1803
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
jaroslav@1258
  1804
         * </ul>
jaroslav@1258
  1805
         */
jaroslav@1258
  1806
        TIMED_WAITING,
jaroslav@1258
  1807
jaroslav@1258
  1808
        /**
jaroslav@1258
  1809
         * Thread state for a terminated thread.
jaroslav@1258
  1810
         * The thread has completed execution.
jaroslav@1258
  1811
         */
jaroslav@1258
  1812
        TERMINATED;
jaroslav@1258
  1813
    }
jaroslav@1258
  1814
jaroslav@1258
  1815
    /**
jaroslav@1258
  1816
     * Returns the state of this thread.
jaroslav@1258
  1817
     * This method is designed for use in monitoring of the system state,
jaroslav@1258
  1818
     * not for synchronization control.
jaroslav@1258
  1819
     *
jaroslav@1258
  1820
     * @return this thread's state.
jaroslav@1258
  1821
     * @since 1.5
jaroslav@1258
  1822
     */
jaroslav@1258
  1823
    public State getState() {
jaroslav@1258
  1824
        // get current thread state
jaroslav@1258
  1825
        return sun.misc.VM.toThreadState(threadStatus);
jaroslav@1258
  1826
    }
jaroslav@1258
  1827
jaroslav@1258
  1828
    // Added in JSR-166
jaroslav@1258
  1829
jaroslav@1258
  1830
    /**
jaroslav@1258
  1831
     * Interface for handlers invoked when a <tt>Thread</tt> abruptly
jaroslav@1258
  1832
     * terminates due to an uncaught exception.
jaroslav@1258
  1833
     * <p>When a thread is about to terminate due to an uncaught exception
jaroslav@1258
  1834
     * the Java Virtual Machine will query the thread for its
jaroslav@1258
  1835
     * <tt>UncaughtExceptionHandler</tt> using
jaroslav@1258
  1836
     * {@link #getUncaughtExceptionHandler} and will invoke the handler's
jaroslav@1258
  1837
     * <tt>uncaughtException</tt> method, passing the thread and the
jaroslav@1258
  1838
     * exception as arguments.
jaroslav@1258
  1839
     * If a thread has not had its <tt>UncaughtExceptionHandler</tt>
jaroslav@1258
  1840
     * explicitly set, then its <tt>ThreadGroup</tt> object acts as its
jaroslav@1258
  1841
     * <tt>UncaughtExceptionHandler</tt>. If the <tt>ThreadGroup</tt> object
jaroslav@1258
  1842
     * has no
jaroslav@1258
  1843
     * special requirements for dealing with the exception, it can forward
jaroslav@1258
  1844
     * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler
jaroslav@1258
  1845
     * default uncaught exception handler}.
jaroslav@1258
  1846
     *
jaroslav@1258
  1847
     * @see #setDefaultUncaughtExceptionHandler
jaroslav@1258
  1848
     * @see #setUncaughtExceptionHandler
jaroslav@1258
  1849
     * @see ThreadGroup#uncaughtException
jaroslav@1258
  1850
     * @since 1.5
jaroslav@1258
  1851
     */
jaroslav@1258
  1852
    public interface UncaughtExceptionHandler {
jaroslav@1258
  1853
        /**
jaroslav@1258
  1854
         * Method invoked when the given thread terminates due to the
jaroslav@1258
  1855
         * given uncaught exception.
jaroslav@1258
  1856
         * <p>Any exception thrown by this method will be ignored by the
jaroslav@1258
  1857
         * Java Virtual Machine.
jaroslav@1258
  1858
         * @param t the thread
jaroslav@1258
  1859
         * @param e the exception
jaroslav@1258
  1860
         */
jaroslav@1258
  1861
        void uncaughtException(Thread t, Throwable e);
jaroslav@1258
  1862
    }
jaroslav@1258
  1863
jaroslav@1258
  1864
    // null unless explicitly set
jaroslav@1258
  1865
    private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
jaroslav@1258
  1866
jaroslav@1258
  1867
    // null unless explicitly set
jaroslav@1258
  1868
    private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
jaroslav@1258
  1869
jaroslav@1258
  1870
    /**
jaroslav@1258
  1871
     * Set the default handler invoked when a thread abruptly terminates
jaroslav@1258
  1872
     * due to an uncaught exception, and no other handler has been defined
jaroslav@1258
  1873
     * for that thread.
jaroslav@1258
  1874
     *
jaroslav@1258
  1875
     * <p>Uncaught exception handling is controlled first by the thread, then
jaroslav@1258
  1876
     * by the thread's {@link ThreadGroup} object and finally by the default
jaroslav@1258
  1877
     * uncaught exception handler. If the thread does not have an explicit
jaroslav@1258
  1878
     * uncaught exception handler set, and the thread's thread group
jaroslav@1258
  1879
     * (including parent thread groups)  does not specialize its
jaroslav@1258
  1880
     * <tt>uncaughtException</tt> method, then the default handler's
jaroslav@1258
  1881
     * <tt>uncaughtException</tt> method will be invoked.
jaroslav@1258
  1882
     * <p>By setting the default uncaught exception handler, an application
jaroslav@1258
  1883
     * can change the way in which uncaught exceptions are handled (such as
jaroslav@1258
  1884
     * logging to a specific device, or file) for those threads that would
jaroslav@1258
  1885
     * already accept whatever &quot;default&quot; behavior the system
jaroslav@1258
  1886
     * provided.
jaroslav@1258
  1887
     *
jaroslav@1258
  1888
     * <p>Note that the default uncaught exception handler should not usually
jaroslav@1258
  1889
     * defer to the thread's <tt>ThreadGroup</tt> object, as that could cause
jaroslav@1258
  1890
     * infinite recursion.
jaroslav@1258
  1891
     *
jaroslav@1258
  1892
     * @param eh the object to use as the default uncaught exception handler.
jaroslav@1258
  1893
     * If <tt>null</tt> then there is no default handler.
jaroslav@1258
  1894
     *
jaroslav@1258
  1895
     * @throws SecurityException if a security manager is present and it
jaroslav@1258
  1896
     *         denies <tt>{@link RuntimePermission}
jaroslav@1258
  1897
     *         (&quot;setDefaultUncaughtExceptionHandler&quot;)</tt>
jaroslav@1258
  1898
     *
jaroslav@1258
  1899
     * @see #setUncaughtExceptionHandler
jaroslav@1258
  1900
     * @see #getUncaughtExceptionHandler
jaroslav@1258
  1901
     * @see ThreadGroup#uncaughtException
jaroslav@1258
  1902
     * @since 1.5
jaroslav@1258
  1903
     */
jaroslav@1258
  1904
    public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
jaroslav@1258
  1905
        SecurityManager sm = System.getSecurityManager();
jaroslav@1258
  1906
        if (sm != null) {
jaroslav@1258
  1907
            sm.checkPermission(
jaroslav@1258
  1908
                new RuntimePermission("setDefaultUncaughtExceptionHandler")
jaroslav@1258
  1909
                    );
jaroslav@1258
  1910
        }
jaroslav@1258
  1911
jaroslav@1258
  1912
         defaultUncaughtExceptionHandler = eh;
jaroslav@1258
  1913
     }
jaroslav@1258
  1914
jaroslav@1258
  1915
    /**
jaroslav@1258
  1916
     * Returns the default handler invoked when a thread abruptly terminates
jaroslav@1258
  1917
     * due to an uncaught exception. If the returned value is <tt>null</tt>,
jaroslav@1258
  1918
     * there is no default.
jaroslav@1258
  1919
     * @since 1.5
jaroslav@1258
  1920
     * @see #setDefaultUncaughtExceptionHandler
jaroslav@1258
  1921
     */
jaroslav@1258
  1922
    public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
jaroslav@1258
  1923
        return defaultUncaughtExceptionHandler;
jaroslav@1258
  1924
    }
jaroslav@1258
  1925
jaroslav@1258
  1926
    /**
jaroslav@1258
  1927
     * Returns the handler invoked when this thread abruptly terminates
jaroslav@1258
  1928
     * due to an uncaught exception. If this thread has not had an
jaroslav@1258
  1929
     * uncaught exception handler explicitly set then this thread's
jaroslav@1258
  1930
     * <tt>ThreadGroup</tt> object is returned, unless this thread
jaroslav@1258
  1931
     * has terminated, in which case <tt>null</tt> is returned.
jaroslav@1258
  1932
     * @since 1.5
jaroslav@1258
  1933
     */
jaroslav@1258
  1934
    public UncaughtExceptionHandler getUncaughtExceptionHandler() {
jaroslav@1258
  1935
        return uncaughtExceptionHandler != null ?
jaroslav@1258
  1936
            uncaughtExceptionHandler : group;
jaroslav@1258
  1937
    }
jaroslav@1258
  1938
jaroslav@1258
  1939
    /**
jaroslav@1258
  1940
     * Set the handler invoked when this thread abruptly terminates
jaroslav@1258
  1941
     * due to an uncaught exception.
jaroslav@1258
  1942
     * <p>A thread can take full control of how it responds to uncaught
jaroslav@1258
  1943
     * exceptions by having its uncaught exception handler explicitly set.
jaroslav@1258
  1944
     * If no such handler is set then the thread's <tt>ThreadGroup</tt>
jaroslav@1258
  1945
     * object acts as its handler.
jaroslav@1258
  1946
     * @param eh the object to use as this thread's uncaught exception
jaroslav@1258
  1947
     * handler. If <tt>null</tt> then this thread has no explicit handler.
jaroslav@1258
  1948
     * @throws  SecurityException  if the current thread is not allowed to
jaroslav@1258
  1949
     *          modify this thread.
jaroslav@1258
  1950
     * @see #setDefaultUncaughtExceptionHandler
jaroslav@1258
  1951
     * @see ThreadGroup#uncaughtException
jaroslav@1258
  1952
     * @since 1.5
jaroslav@1258
  1953
     */
jaroslav@1258
  1954
    public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
jaroslav@1258
  1955
        checkAccess();
jaroslav@1258
  1956
        uncaughtExceptionHandler = eh;
jaroslav@1258
  1957
    }
jaroslav@1258
  1958
jaroslav@1258
  1959
    /**
jaroslav@1258
  1960
     * Dispatch an uncaught exception to the handler. This method is
jaroslav@1258
  1961
     * intended to be called only by the JVM.
jaroslav@1258
  1962
     */
jaroslav@1258
  1963
    private void dispatchUncaughtException(Throwable e) {
jaroslav@1258
  1964
        getUncaughtExceptionHandler().uncaughtException(this, e);
jaroslav@1258
  1965
    }
jaroslav@1258
  1966
jaroslav@1258
  1967
    /**
jaroslav@1258
  1968
     * Removes from the specified map any keys that have been enqueued
jaroslav@1258
  1969
     * on the specified reference queue.
jaroslav@1258
  1970
     */
jaroslav@1258
  1971
    static void processQueue(ReferenceQueue<Class<?>> queue,
jaroslav@1258
  1972
                             ConcurrentMap<? extends
jaroslav@1258
  1973
                             WeakReference<Class<?>>, ?> map)
jaroslav@1258
  1974
    {
jaroslav@1258
  1975
        Reference<? extends Class<?>> ref;
jaroslav@1258
  1976
        while((ref = queue.poll()) != null) {
jaroslav@1258
  1977
            map.remove(ref);
jaroslav@1258
  1978
        }
jaroslav@1258
  1979
    }
jaroslav@1258
  1980
jaroslav@1258
  1981
    /**
jaroslav@1258
  1982
     *  Weak key for Class objects.
jaroslav@1258
  1983
     **/
jaroslav@1258
  1984
    static class WeakClassKey extends WeakReference<Class<?>> {
jaroslav@1258
  1985
        /**
jaroslav@1258
  1986
         * saved value of the referent's identity hash code, to maintain
jaroslav@1258
  1987
         * a consistent hash code after the referent has been cleared
jaroslav@1258
  1988
         */
jaroslav@1258
  1989
        private final int hash;
jaroslav@1258
  1990
jaroslav@1258
  1991
        /**
jaroslav@1258
  1992
         * Create a new WeakClassKey to the given object, registered
jaroslav@1258
  1993
         * with a queue.
jaroslav@1258
  1994
         */
jaroslav@1258
  1995
        WeakClassKey(Class<?> cl, ReferenceQueue<Class<?>> refQueue) {
jaroslav@1258
  1996
            super(cl, refQueue);
jaroslav@1258
  1997
            hash = System.identityHashCode(cl);
jaroslav@1258
  1998
        }
jaroslav@1258
  1999
jaroslav@1258
  2000
        /**
jaroslav@1258
  2001
         * Returns the identity hash code of the original referent.
jaroslav@1258
  2002
         */
jaroslav@1258
  2003
        @Override
jaroslav@1258
  2004
        public int hashCode() {
jaroslav@1258
  2005
            return hash;
jaroslav@1258
  2006
        }
jaroslav@1258
  2007
jaroslav@1258
  2008
        /**
jaroslav@1258
  2009
         * Returns true if the given object is this identical
jaroslav@1258
  2010
         * WeakClassKey instance, or, if this object's referent has not
jaroslav@1258
  2011
         * been cleared, if the given object is another WeakClassKey
jaroslav@1258
  2012
         * instance with the identical non-null referent as this one.
jaroslav@1258
  2013
         */
jaroslav@1258
  2014
        @Override
jaroslav@1258
  2015
        public boolean equals(Object obj) {
jaroslav@1258
  2016
            if (obj == this)
jaroslav@1258
  2017
                return true;
jaroslav@1258
  2018
jaroslav@1258
  2019
            if (obj instanceof WeakClassKey) {
jaroslav@1258
  2020
                Object referent = get();
jaroslav@1258
  2021
                return (referent != null) &&
jaroslav@1258
  2022
                       (referent == ((WeakClassKey) obj).get());
jaroslav@1258
  2023
            } else {
jaroslav@1258
  2024
                return false;
jaroslav@1258
  2025
            }
jaroslav@1258
  2026
        }
jaroslav@1258
  2027
    }
jaroslav@1258
  2028
jaroslav@1258
  2029
    /* Some private helper methods */
jaroslav@1258
  2030
    private native void setPriority0(int newPriority);
jaroslav@1258
  2031
    private native void stop0(Object o);
jaroslav@1258
  2032
    private native void suspend0();
jaroslav@1258
  2033
    private native void resume0();
jaroslav@1258
  2034
    private native void interrupt0();
jaroslav@1258
  2035
}