Thread.java revision 23122dc6c511936935ceaccaed94adafdc9fddaf
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17/*
18 * Copyright (C) 2008 The Android Open Source Project
19 *
20 * Licensed under the Apache License, Version 2.0 (the "License");
21 * you may not use this file except in compliance with the License.
22 * You may obtain a copy of the License at
23 *
24 *      http://www.apache.org/licenses/LICENSE-2.0
25 *
26 * Unless required by applicable law or agreed to in writing, software
27 * distributed under the License is distributed on an "AS IS" BASIS,
28 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29 * See the License for the specific language governing permissions and
30 * limitations under the License.
31 */
32
33package java.lang;
34
35import dalvik.system.VMStack;
36import java.util.ArrayList;
37import java.util.HashMap;
38import java.util.List;
39import java.util.Map;
40import libcore.util.EmptyArray;
41
42/**
43 * A {@code Thread} is a concurrent unit of execution. It has its own call stack
44 * for methods being invoked, their arguments and local variables. Each application
45 * has at least one thread running when it is started, the main thread, in the main
46 * {@link ThreadGroup}. The runtime keeps its own threads in the system thread
47 * group.
48 *
49 * <p>There are two ways to execute code in a new thread.
50 * You can either subclass {@code Thread} and overriding its {@link #run()} method,
51 * or construct a new {@code Thread} and pass a {@link Runnable} to the constructor.
52 * In either case, the {@link #start()} method must be called to actually execute
53 * the new {@code Thread}.
54 *
55 * <p>Each {@code Thread} has an integer priority that affect how the thread is
56 * scheduled by the OS. A new thread inherits the priority of its parent.
57 * A thread's priority can be set using the {@link #setPriority(int)} method.
58 */
59public class Thread implements Runnable {
60    private static final int NANOS_PER_MILLI = 1000000;
61
62    /** Park states */
63    private static class ParkState {
64        /** park state indicating unparked */
65        private static final int UNPARKED = 1;
66
67        /** park state indicating preemptively unparked */
68        private static final int PREEMPTIVELY_UNPARKED = 2;
69
70        /** park state indicating parked */
71        private static final int PARKED = 3;
72    }
73
74    /**
75     * A representation of a thread's state. A given thread may only be in one
76     * state at a time.
77     */
78    public enum State {
79        /**
80         * The thread has been created, but has never been started.
81         */
82        NEW,
83        /**
84         * The thread may be run.
85         */
86        RUNNABLE,
87        /**
88         * The thread is blocked and waiting for a lock.
89         */
90        BLOCKED,
91        /**
92         * The thread is waiting.
93         */
94        WAITING,
95        /**
96         * The thread is waiting for a specified amount of time.
97         */
98        TIMED_WAITING,
99        /**
100         * The thread has been terminated.
101         */
102        TERMINATED
103    }
104
105    /**
106     * The maximum priority value allowed for a thread.
107     * This corresponds to (but does not have the same value as)
108     * {@code android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY}.
109     */
110    public static final int MAX_PRIORITY = 10;
111
112    /**
113     * The minimum priority value allowed for a thread.
114     * This corresponds to (but does not have the same value as)
115     * {@code android.os.Process.THREAD_PRIORITY_LOWEST}.
116     */
117    public static final int MIN_PRIORITY = 1;
118
119    /**
120     * The normal (default) priority value assigned to the main thread.
121     * This corresponds to (but does not have the same value as)
122     * {@code android.os.Process.THREAD_PRIORITY_DEFAULT}.
123
124     */
125    public static final int NORM_PRIORITY = 5;
126
127    /* Some of these are accessed directly by the VM; do not rename them. */
128    private volatile long nativePeer;
129    volatile ThreadGroup group;
130    volatile boolean daemon;
131    volatile String name;
132    volatile int priority;
133    volatile long stackSize;
134    Runnable target;
135    private static int count = 0;
136
137    /**
138     * Holds the thread's ID. We simply count upwards, so
139     * each Thread has a unique ID.
140     */
141    private long id;
142
143    /**
144     * Normal thread local values.
145     */
146    ThreadLocal.Values localValues;
147
148    /**
149     * Inheritable thread local values.
150     */
151    ThreadLocal.Values inheritableValues;
152
153    /** Callbacks to run on interruption. */
154    private final List<Runnable> interruptActions = new ArrayList<Runnable>();
155
156    /**
157     * Holds the class loader for this Thread, in case there is one.
158     */
159    private ClassLoader contextClassLoader;
160
161    /**
162     * Holds the handler for uncaught exceptions in this Thread,
163     * in case there is one.
164     */
165    private UncaughtExceptionHandler uncaughtHandler;
166
167    /**
168     * Holds the default handler for uncaught exceptions, in case there is one.
169     */
170    private static UncaughtExceptionHandler defaultUncaughtHandler;
171
172    /**
173     * Reflects whether this Thread has already been started. A Thread
174     * can only be started once (no recycling). Also, we need it to deduce
175     * the proper Thread status.
176     */
177    boolean hasBeenStarted = false;
178
179    /** the park state of the thread */
180    private int parkState = ParkState.UNPARKED;
181
182    /**
183     * The synchronization object responsible for this thread's join/sleep/park operations.
184     */
185    private final Object lock = new Object();
186
187    /** Looked up reflectively and used by java.util.concurrent.locks.LockSupport. */
188    private Object parkBlocker;
189
190    /**
191     * Constructs a new {@code Thread} with no {@code Runnable} object and a
192     * newly generated name. The new {@code Thread} will belong to the same
193     * {@code ThreadGroup} as the {@code Thread} calling this constructor.
194     *
195     * @see java.lang.ThreadGroup
196     * @see java.lang.Runnable
197     */
198    public Thread() {
199        create(null, null, null, 0);
200    }
201
202    /**
203     * Constructs a new {@code Thread} with a {@code Runnable} object and a
204     * newly generated name. The new {@code Thread} will belong to the same
205     * {@code ThreadGroup} as the {@code Thread} calling this constructor.
206     *
207     * @param runnable
208     *            a {@code Runnable} whose method <code>run</code> will be
209     *            executed by the new {@code Thread}
210     *
211     * @see java.lang.ThreadGroup
212     * @see java.lang.Runnable
213     */
214    public Thread(Runnable runnable) {
215        create(null, runnable, null, 0);
216    }
217
218    /**
219     * Constructs a new {@code Thread} with a {@code Runnable} object and name
220     * provided. The new {@code Thread} will belong to the same {@code
221     * ThreadGroup} as the {@code Thread} calling this constructor.
222     *
223     * @param runnable
224     *            a {@code Runnable} whose method <code>run</code> will be
225     *            executed by the new {@code Thread}
226     * @param threadName
227     *            the name for the {@code Thread} being created
228     *
229     * @see java.lang.ThreadGroup
230     * @see java.lang.Runnable
231     */
232    public Thread(Runnable runnable, String threadName) {
233        if (threadName == null) {
234            throw new NullPointerException("threadName == null");
235        }
236
237        create(null, runnable, threadName, 0);
238    }
239
240    /**
241     * Constructs a new {@code Thread} with no {@code Runnable} object and the
242     * name provided. The new {@code Thread} will belong to the same {@code
243     * ThreadGroup} as the {@code Thread} calling this constructor.
244     *
245     * @param threadName
246     *            the name for the {@code Thread} being created
247     *
248     * @see java.lang.ThreadGroup
249     * @see java.lang.Runnable
250     *
251     */
252    public Thread(String threadName) {
253        if (threadName == null) {
254            throw new NullPointerException("threadName == null");
255        }
256
257        create(null, null, threadName, 0);
258    }
259
260    /**
261     * Constructs a new {@code Thread} with a {@code Runnable} object and a
262     * newly generated name. The new {@code Thread} will belong to the {@code
263     * ThreadGroup} passed as parameter.
264     *
265     * @param group
266     *            {@code ThreadGroup} to which the new {@code Thread} will
267     *            belong
268     * @param runnable
269     *            a {@code Runnable} whose method <code>run</code> will be
270     *            executed by the new {@code Thread}
271     * @throws IllegalThreadStateException
272     *             if <code>group.destroy()</code> has already been done
273     * @see java.lang.ThreadGroup
274     * @see java.lang.Runnable
275     */
276    public Thread(ThreadGroup group, Runnable runnable) {
277        create(group, runnable, null, 0);
278    }
279
280    /**
281     * Constructs a new {@code Thread} with a {@code Runnable} object, the given
282     * name and belonging to the {@code ThreadGroup} passed as parameter.
283     *
284     * @param group
285     *            ThreadGroup to which the new {@code Thread} will belong
286     * @param runnable
287     *            a {@code Runnable} whose method <code>run</code> will be
288     *            executed by the new {@code Thread}
289     * @param threadName
290     *            the name for the {@code Thread} being created
291     * @throws IllegalThreadStateException
292     *             if <code>group.destroy()</code> has already been done
293     * @see java.lang.ThreadGroup
294     * @see java.lang.Runnable
295     */
296    public Thread(ThreadGroup group, Runnable runnable, String threadName) {
297        if (threadName == null) {
298            throw new NullPointerException("threadName == null");
299        }
300
301        create(group, runnable, threadName, 0);
302    }
303
304    /**
305     * Constructs a new {@code Thread} with no {@code Runnable} object, the
306     * given name and belonging to the {@code ThreadGroup} passed as parameter.
307     *
308     * @param group
309     *            {@code ThreadGroup} to which the new {@code Thread} will belong
310     * @param threadName
311     *            the name for the {@code Thread} being created
312     * @throws IllegalThreadStateException
313     *             if <code>group.destroy()</code> has already been done
314     * @see java.lang.ThreadGroup
315     * @see java.lang.Runnable
316     */
317    public Thread(ThreadGroup group, String threadName) {
318        if (threadName == null) {
319            throw new NullPointerException("threadName == null");
320        }
321
322        create(group, null, threadName, 0);
323    }
324
325    /**
326     * Constructs a new {@code Thread} with a {@code Runnable} object, the given
327     * name and belonging to the {@code ThreadGroup} passed as parameter.
328     *
329     * @param group
330     *            {@code ThreadGroup} to which the new {@code Thread} will
331     *            belong
332     * @param runnable
333     *            a {@code Runnable} whose method <code>run</code> will be
334     *            executed by the new {@code Thread}
335     * @param threadName
336     *            the name for the {@code Thread} being created
337     * @param stackSize
338     *            a stack size for the new {@code Thread}. This has a highly
339     *            platform-dependent interpretation. It may even be ignored
340     *            completely.
341     * @throws IllegalThreadStateException
342     *             if <code>group.destroy()</code> has already been done
343     * @see java.lang.ThreadGroup
344     * @see java.lang.Runnable
345     */
346    public Thread(ThreadGroup group, Runnable runnable, String threadName, long stackSize) {
347        if (threadName == null) {
348            throw new NullPointerException("threadName == null");
349        }
350        create(group, runnable, threadName, stackSize);
351    }
352
353    /**
354     * Package-scope method invoked by Dalvik VM to create "internal"
355     * threads or attach threads created externally.
356     *
357     * Don't call Thread.currentThread(), since there may not be such
358     * a thing (e.g. for Main).
359     */
360    Thread(ThreadGroup group, String name, int priority, boolean daemon) {
361        synchronized (Thread.class) {
362            id = ++Thread.count;
363        }
364
365        if (name == null) {
366            this.name = "Thread-" + id;
367        } else {
368            this.name = name;
369        }
370
371        if (group == null) {
372            throw new InternalError("group == null");
373        }
374
375        this.group = group;
376
377        this.target = null;
378        this.stackSize = 0;
379        this.priority = priority;
380        this.daemon = daemon;
381
382        /* add ourselves to our ThreadGroup of choice */
383        this.group.addThread(this);
384    }
385
386    /**
387     * Initializes a new, existing Thread object with a runnable object,
388     * the given name and belonging to the ThreadGroup passed as parameter.
389     * This is the method that the several public constructors delegate their
390     * work to.
391     *
392     * @param group ThreadGroup to which the new Thread will belong
393     * @param runnable a java.lang.Runnable whose method <code>run</code> will
394     *        be executed by the new Thread
395     * @param threadName Name for the Thread being created
396     * @param stackSize Platform dependent stack size
397     * @throws IllegalThreadStateException if <code>group.destroy()</code> has
398     *         already been done
399     * @see java.lang.ThreadGroup
400     * @see java.lang.Runnable
401     */
402    private void create(ThreadGroup group, Runnable runnable, String threadName, long stackSize) {
403        Thread currentThread = Thread.currentThread();
404        if (group == null) {
405            group = currentThread.getThreadGroup();
406        }
407
408        if (group.isDestroyed()) {
409            throw new IllegalThreadStateException("Group already destroyed");
410        }
411
412        this.group = group;
413
414        synchronized (Thread.class) {
415            id = ++Thread.count;
416        }
417
418        if (threadName == null) {
419            this.name = "Thread-" + id;
420        } else {
421            this.name = threadName;
422        }
423
424        this.target = runnable;
425        this.stackSize = stackSize;
426
427        this.priority = currentThread.getPriority();
428
429        this.contextClassLoader = currentThread.contextClassLoader;
430
431        // Transfer over InheritableThreadLocals.
432        if (currentThread.inheritableValues != null) {
433            inheritableValues = new ThreadLocal.Values(currentThread.inheritableValues);
434        }
435
436        // add ourselves to our ThreadGroup of choice
437        this.group.addThread(this);
438    }
439
440    /**
441     * Returns the number of active {@code Thread}s in the running {@code
442     * Thread}'s group and its subgroups.
443     *
444     * @return the number of {@code Thread}s
445     */
446    public static int activeCount() {
447        return currentThread().getThreadGroup().activeCount();
448    }
449
450    /**
451     * Does nothing.
452     */
453    public final void checkAccess() {
454    }
455
456    /**
457     * Returns the number of stack frames in this thread.
458     *
459     * @return Number of stack frames
460     * @deprecated The results of this call were never well defined. To make
461     *             things worse, it would depend on whether the Thread was
462     *             suspended or not, and suspend was deprecated too.
463     */
464    @Deprecated
465    public int countStackFrames() {
466        return getStackTrace().length;
467    }
468
469    /**
470     * Returns the Thread of the caller, that is, the current Thread.
471     */
472    public static native Thread currentThread();
473
474    /**
475     * Throws {@code UnsupportedOperationException}.
476     * @deprecated Not implemented.
477     */
478    @Deprecated
479    public void destroy() {
480        throw new UnsupportedOperationException();
481    }
482
483    /**
484     * Prints to the standard error stream a text representation of the current
485     * stack for this Thread.
486     *
487     * @see Throwable#printStackTrace()
488     */
489    public static void dumpStack() {
490        new Throwable("stack dump").printStackTrace();
491    }
492
493    /**
494     * Copies an array with all Threads which are in the same ThreadGroup as the
495     * receiver - and subgroups - into the array <code>threads</code> passed as
496     * parameter. If the array passed as parameter is too small no exception is
497     * thrown - the extra elements are simply not copied.
498     *
499     * @param threads
500     *            array into which the Threads will be copied
501     * @return How many Threads were copied over
502     */
503    public static int enumerate(Thread[] threads) {
504        Thread thread = Thread.currentThread();
505        return thread.getThreadGroup().enumerate(threads);
506    }
507
508    /**
509     * Returns a map of all the currently live threads to their stack traces.
510     */
511    public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
512        Map<Thread, StackTraceElement[]> map = new HashMap<Thread, StackTraceElement[]>();
513
514        // Find out how many live threads we have. Allocate a bit more
515        // space than needed, in case new ones are just being created.
516        int count = ThreadGroup.systemThreadGroup.activeCount();
517        Thread[] threads = new Thread[count + count / 2];
518
519        // Enumerate the threads and collect the stacktraces.
520        count = ThreadGroup.systemThreadGroup.enumerate(threads);
521        for (int i = 0; i < count; i++) {
522            map.put(threads[i], threads[i].getStackTrace());
523        }
524
525        return map;
526    }
527
528    /**
529     * Returns the context ClassLoader for this Thread.
530     *
531     * @return ClassLoader The context ClassLoader
532     * @see java.lang.ClassLoader
533     * @see #getContextClassLoader()
534     */
535    public ClassLoader getContextClassLoader() {
536        return contextClassLoader;
537    }
538
539    /**
540     * Returns the default exception handler that's executed when uncaught
541     * exception terminates a thread.
542     *
543     * @return an {@link UncaughtExceptionHandler} or <code>null</code> if
544     *         none exists.
545     */
546    public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() {
547        return defaultUncaughtHandler;
548    }
549
550    /**
551     * Returns the thread's identifier. The ID is a positive <code>long</code>
552     * generated on thread creation, is unique to the thread, and doesn't change
553     * during the lifetime of the thread; the ID may be reused after the thread
554     * has been terminated.
555     *
556     * @return the thread's ID.
557     */
558    public long getId() {
559        return id;
560    }
561
562    /**
563     * Returns the name of the Thread.
564     */
565    public final String getName() {
566        return name;
567    }
568
569    /**
570     * Returns the priority of the Thread.
571     */
572    public final int getPriority() {
573        return priority;
574    }
575
576    /**
577     * Returns an array of {@link StackTraceElement} representing the current thread's stack.
578     */
579    public StackTraceElement[] getStackTrace() {
580        StackTraceElement ste[] = VMStack.getThreadStackTrace(this);
581        return ste != null ? ste : EmptyArray.STACK_TRACE_ELEMENT;
582    }
583
584    /**
585     * Returns the current state of the Thread. This method is useful for
586     * monitoring purposes.
587     *
588     * @return a {@link State} value.
589     */
590    public State getState() {
591        return State.values()[nativeGetStatus(hasBeenStarted)];
592    }
593
594    private native int nativeGetStatus(boolean hasBeenStarted);
595
596    /**
597     * Returns the ThreadGroup to which this Thread belongs.
598     *
599     * @return the Thread's ThreadGroup
600     */
601    public final ThreadGroup getThreadGroup() {
602        // TODO This should actually be done at native termination.
603        if (getState() == Thread.State.TERMINATED) {
604            return null;
605        } else {
606            return group;
607        }
608    }
609
610    /**
611     * Returns the thread's uncaught exception handler. If not explicitly set,
612     * then the ThreadGroup's handler is returned. If the thread is terminated,
613     * then <code>null</code> is returned.
614     *
615     * @return an {@link UncaughtExceptionHandler} instance or {@code null}.
616     */
617    public UncaughtExceptionHandler getUncaughtExceptionHandler() {
618        if (uncaughtHandler != null) {
619            return uncaughtHandler;
620        } else {
621            return group;           // ThreadGroup is instance of UEH
622        }
623    }
624
625    /**
626     * Posts an interrupt request to this {@code Thread}. The behavior depends on
627     * the state of this {@code Thread}:
628     * <ul>
629     * <li>
630     * {@code Thread}s blocked in one of {@code Object}'s {@code wait()} methods
631     * or one of {@code Thread}'s {@code join()} or {@code sleep()} methods will
632     * be woken up, their interrupt status will be cleared, and they receive an
633     * {@link InterruptedException}.
634     * <li>
635     * {@code Thread}s blocked in an I/O operation of an
636     * {@link java.nio.channels.InterruptibleChannel} will have their interrupt
637     * status set and receive an
638     * {@link java.nio.channels.ClosedByInterruptException}. Also, the channel
639     * will be closed.
640     * <li>
641     * {@code Thread}s blocked in a {@link java.nio.channels.Selector} will have
642     * their interrupt status set and return immediately. They don't receive an
643     * exception in this case.
644     * <ul>
645     *
646     * @see Thread#interrupted
647     * @see Thread#isInterrupted
648     */
649    public void interrupt() {
650        // Interrupt this thread before running actions so that other
651        // threads that observe the interrupt as a result of an action
652        // will see that this thread is in the interrupted state.
653        nativeInterrupt();
654
655        synchronized (interruptActions) {
656            for (int i = interruptActions.size() - 1; i >= 0; i--) {
657                interruptActions.get(i).run();
658            }
659        }
660    }
661
662    private native void nativeInterrupt();
663
664    /**
665     * Returns a <code>boolean</code> indicating whether the current Thread (
666     * <code>currentThread()</code>) has a pending interrupt request (<code>
667     * true</code>) or not (<code>false</code>). It also has the side-effect of
668     * clearing the flag.
669     *
670     * @return a <code>boolean</code> indicating the interrupt status
671     * @see Thread#currentThread
672     * @see Thread#interrupt
673     * @see Thread#isInterrupted
674     */
675    public static native boolean interrupted();
676
677    /**
678     * Returns <code>true</code> if the receiver has already been started and
679     * still runs code (hasn't died yet). Returns <code>false</code> either if
680     * the receiver hasn't been started yet or if it has already started and run
681     * to completion and died.
682     *
683     * @return a <code>boolean</code> indicating the liveness of the Thread
684     * @see Thread#start
685     */
686    public final boolean isAlive() {
687        return (nativePeer != 0);
688    }
689
690    /**
691     * Tests whether this is a daemon thread.
692     * A daemon thread only runs as long as there are non-daemon threads running.
693     * When the last non-daemon thread ends, the runtime will exit. This is not
694     * normally relevant to applications with a UI.
695     */
696    public final boolean isDaemon() {
697        return daemon;
698    }
699
700    /**
701     * Returns a <code>boolean</code> indicating whether the receiver has a
702     * pending interrupt request (<code>true</code>) or not (
703     * <code>false</code>)
704     *
705     * @return a <code>boolean</code> indicating the interrupt status
706     * @see Thread#interrupt
707     * @see Thread#interrupted
708     */
709    public native boolean isInterrupted();
710
711    /**
712     * Blocks the current Thread (<code>Thread.currentThread()</code>) until
713     * the receiver finishes its execution and dies.
714     *
715     * @throws InterruptedException if the current thread has been interrupted.
716     *         The interrupted status of the current thread will be cleared before the exception is
717     *         thrown.
718     * @see Object#notifyAll
719     * @see java.lang.ThreadDeath
720     */
721    public final void join() throws InterruptedException {
722        synchronized (lock) {
723            while (isAlive()) {
724                lock.wait();
725            }
726        }
727    }
728
729    /**
730     * Blocks the current Thread (<code>Thread.currentThread()</code>) until
731     * the receiver finishes its execution and dies or the specified timeout
732     * expires, whatever happens first.
733     *
734     * <p>A timeout of zero means the calling thread should wait forever unless interrupted.
735     *
736     * @param millis The maximum time to wait (in milliseconds).
737     * @throws InterruptedException if the current thread has been interrupted.
738     *         The interrupted status of the current thread will be cleared before the exception is
739     *         thrown.
740     * @see Object#notifyAll
741     * @see java.lang.ThreadDeath
742     */
743    public final void join(long millis) throws InterruptedException {
744        join(millis, 0);
745    }
746
747    /**
748     * Blocks the current Thread (<code>Thread.currentThread()</code>) until
749     * the receiver finishes its execution and dies or the specified timeout
750     * expires, whatever happens first.
751     *
752     * <p>A timeout of zero means the calling thread should wait forever unless interrupted.
753     *
754     * @param millis The maximum time to wait (in milliseconds).
755     * @param nanos Extra nanosecond precision
756     * @throws InterruptedException if the current thread has been interrupted.
757     *         The interrupted status of the current thread will be cleared before the exception is
758     *         thrown.
759     * @see Object#notifyAll
760     * @see java.lang.ThreadDeath
761     */
762    public final void join(long millis, int nanos) throws InterruptedException {
763        if (millis < 0 || nanos < 0 || nanos >= NANOS_PER_MILLI) {
764            throw new IllegalArgumentException("bad timeout: millis=" + millis + ",nanos=" + nanos);
765        }
766
767        // avoid overflow: if total > 292,277 years, just wait forever
768        boolean overflow = millis >= (Long.MAX_VALUE - nanos) / NANOS_PER_MILLI;
769        boolean forever = (millis | nanos) == 0;
770        if (forever | overflow) {
771            join();
772            return;
773        }
774
775        synchronized (lock) {
776            if (!isAlive()) {
777                return;
778            }
779
780            // guaranteed not to overflow
781            long nanosToWait = millis * NANOS_PER_MILLI + nanos;
782
783            // wait until this thread completes or the timeout has elapsed
784            long start = System.nanoTime();
785            while (true) {
786                lock.wait(millis, nanos);
787                if (!isAlive()) {
788                    break;
789                }
790                long nanosElapsed = System.nanoTime() - start;
791                long nanosRemaining = nanosToWait - nanosElapsed;
792                if (nanosRemaining <= 0) {
793                    break;
794                }
795                millis = nanosRemaining / NANOS_PER_MILLI;
796                nanos = (int) (nanosRemaining - millis * NANOS_PER_MILLI);
797            }
798        }
799    }
800
801    /**
802     * Throws {@code UnsupportedOperationException}.
803     * @deprecated Only useful in conjunction with deprecated method {@link Thread#suspend}.
804     */
805    @Deprecated
806    public final void resume() {
807        throw new UnsupportedOperationException();
808    }
809
810    /**
811     * Calls the <code>run()</code> method of the Runnable object the receiver
812     * holds. If no Runnable is set, does nothing.
813     *
814     * @see Thread#start
815     */
816    public void run() {
817        if (target != null) {
818            target.run();
819        }
820    }
821
822    /**
823     * Set the context ClassLoader for the receiver.
824     *
825     * @param cl The context ClassLoader
826     * @see #getContextClassLoader()
827     */
828    public void setContextClassLoader(ClassLoader cl) {
829        contextClassLoader = cl;
830    }
831
832    /**
833     * Marks this thread as a daemon thread.
834     * A daemon thread only runs as long as there are non-daemon threads running.
835     * When the last non-daemon thread ends, the runtime will exit. This is not
836     * normally relevant to applications with a UI.
837     * @throws IllegalThreadStateException - if this thread has already started.
838     */
839    public final void setDaemon(boolean isDaemon) {
840        checkNotStarted();
841
842        if (nativePeer == 0) {
843            daemon = isDaemon;
844        }
845    }
846
847    private void checkNotStarted() {
848        if (hasBeenStarted) {
849            throw new IllegalThreadStateException("Thread already started");
850        }
851    }
852
853    /**
854     * Sets the default uncaught exception handler. This handler is invoked in
855     * case any Thread dies due to an unhandled exception.
856     *
857     * @param handler
858     *            The handler to set or null.
859     */
860    public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler) {
861        Thread.defaultUncaughtHandler = handler;
862    }
863
864    /**
865     * Adds a runnable to be invoked upon interruption. If this thread has
866     * already been interrupted, the runnable will be invoked immediately. The
867     * action should be idempotent as it may be invoked multiple times for a
868     * single interruption.
869     *
870     * <p>Each call to this method must be matched with a corresponding call to
871     * {@link #popInterruptAction$}.
872     *
873     * @hide used by NIO
874     */
875    public final void pushInterruptAction$(Runnable interruptAction) {
876        synchronized (interruptActions) {
877            interruptActions.add(interruptAction);
878        }
879
880        if (interruptAction != null && isInterrupted()) {
881            interruptAction.run();
882        }
883    }
884
885    /**
886     * Removes {@code interruptAction} so it is not invoked upon interruption.
887     *
888     * @param interruptAction the pushed action, used to check that the call
889     *     stack is correctly nested.
890     *
891     * @hide used by NIO
892     */
893    public final void popInterruptAction$(Runnable interruptAction) {
894        synchronized (interruptActions) {
895            Runnable removed = interruptActions.remove(interruptActions.size() - 1);
896            if (interruptAction != removed) {
897                throw new IllegalArgumentException("Expected " + interruptAction + " but was " + removed);
898            }
899        }
900    }
901
902    /**
903     * Sets the name of the Thread.
904     *
905     * @param threadName the new name for the Thread
906     * @see Thread#getName
907     */
908    public final void setName(String threadName) {
909        if (threadName == null) {
910            throw new NullPointerException("threadName == null");
911        }
912        // The lock is taken to ensure no race occurs between starting the
913        // the thread and setting its name (and the name of its native peer).
914        synchronized (this) {
915            this.name = threadName;
916
917            if (isAlive()) {
918                nativeSetName(threadName);
919            }
920        }
921    }
922
923    /**
924     * Tell the VM that the thread's name has changed.  This is useful for
925     * DDMS, which would otherwise be oblivious to Thread.setName calls.
926     */
927    private native void nativeSetName(String newName);
928
929    /**
930     * Sets the priority of this thread. If the requested priority is greater than the
931     * parent thread group's {@link java.lang.ThreadGroup#getMaxPriority}, the group's maximum
932     * priority will be used instead.
933     *
934     * @throws IllegalArgumentException - if the new priority is greater than {@link #MAX_PRIORITY}
935     *     or less than {@link #MIN_PRIORITY}
936     */
937    public final void setPriority(int priority) {
938        if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) {
939            throw new IllegalArgumentException("Priority out of range: " + priority);
940        }
941
942        if (priority > group.getMaxPriority()) {
943            priority = group.getMaxPriority();
944        }
945
946        // The lock is taken to ensure no race occurs between starting the
947        // the thread and setting its priority (and the priority of its native peer).
948        synchronized (this) {
949            this.priority = priority;
950
951            if (isAlive()) {
952                nativeSetPriority(priority);
953            }
954        }
955    }
956
957    private native void nativeSetPriority(int newPriority);
958
959    /**
960     * <p>
961     * Sets the uncaught exception handler. This handler is invoked in case this
962     * Thread dies due to an unhandled exception.
963     * </p>
964     *
965     * @param handler
966     *            The handler to set or <code>null</code>.
967     */
968    public void setUncaughtExceptionHandler(UncaughtExceptionHandler handler) {
969        uncaughtHandler = handler;
970    }
971
972    /**
973     * Causes the thread which sent this message to sleep for the given interval
974     * of time (given in milliseconds). The precision is not guaranteed - the
975     * Thread may sleep more or less than requested.
976     *
977     * @param time
978     *            The time to sleep in milliseconds.
979     * @throws InterruptedException if the current thread has been interrupted.
980     *            The interrupted status of the current thread will be cleared before the exception
981     *            is thrown.
982     * @see Thread#interrupt()
983     */
984    public static void sleep(long time) throws InterruptedException {
985        Thread.sleep(time, 0);
986    }
987
988    /**
989     * Causes the thread which sent this message to sleep for the given interval
990     * of time (given in milliseconds and nanoseconds). The precision is not
991     * guaranteed - the Thread may sleep more or less than requested.
992     *
993     * @param millis
994     *            The time to sleep in milliseconds.
995     * @param nanos
996     *            Extra nanosecond precision
997     * @throws InterruptedException if the current thread has been interrupted.
998     *            The interrupted status of the current thread will be cleared before the exception
999     *            is thrown.
1000     * @see Thread#interrupt()
1001     */
1002    public static void sleep(long millis, int nanos) throws InterruptedException {
1003        // The JLS 3rd edition, section 17.9 says: "...sleep for zero
1004        // time...need not have observable effects."
1005        if (millis == 0 && nanos == 0) {
1006            return;
1007        }
1008
1009        long start = System.nanoTime();
1010        long duration = (millis * NANOS_PER_MILLI) + nanos;
1011
1012        Object lock = currentThread().lock;
1013
1014        // Wait may return early, so loop until sleep duration passes.
1015        synchronized (lock) {
1016            while (true) {
1017                sleep(lock, millis, nanos);
1018
1019                long now = System.nanoTime();
1020                long elapsed = now - start;
1021
1022                if (elapsed >= duration) {
1023                    break;
1024                }
1025
1026                duration -= elapsed;
1027                start = now;
1028                millis = duration / NANOS_PER_MILLI;
1029                nanos = (int) (duration % NANOS_PER_MILLI);
1030            }
1031        }
1032    }
1033
1034    private static native void sleep(Object lock, long millis, int nanos);
1035
1036    /**
1037     * Starts the new Thread of execution. The <code>run()</code> method of
1038     * the receiver will be called by the receiver Thread itself (and not the
1039     * Thread calling <code>start()</code>).
1040     *
1041     * @throws IllegalThreadStateException - if this thread has already started.
1042     * @see Thread#run
1043     */
1044    public synchronized void start() {
1045        checkNotStarted();
1046
1047        hasBeenStarted = true;
1048
1049        nativeCreate(this, stackSize, daemon);
1050    }
1051
1052    private native static void nativeCreate(Thread t, long stackSize, boolean daemon);
1053
1054    /**
1055     * Requests the receiver Thread to stop and throw ThreadDeath. The Thread is
1056     * resumed if it was suspended and awakened if it was sleeping, so that it
1057     * can proceed to throw ThreadDeath.
1058     *
1059     * @deprecated because stopping a thread in this manner is unsafe and can
1060     * leave your application and the VM in an unpredictable state.
1061     */
1062    @Deprecated
1063    public final void stop() {
1064        stop(new ThreadDeath());
1065    }
1066
1067    /**
1068     * Throws {@code UnsupportedOperationException}.
1069     * @deprecated because stopping a thread in this manner is unsafe and can
1070     * leave your application and the VM in an unpredictable state.
1071     */
1072    @Deprecated
1073    public final synchronized void stop(Throwable throwable) {
1074        throw new UnsupportedOperationException();
1075    }
1076
1077    /**
1078     * Throws {@code UnsupportedOperationException}.
1079     * @deprecated May cause deadlocks.
1080     */
1081    @Deprecated
1082    public final void suspend() {
1083        throw new UnsupportedOperationException();
1084    }
1085
1086    /**
1087     * Returns a string containing a concise, human-readable description of the
1088     * Thread. It includes the Thread's name, priority, and group name.
1089     *
1090     * @return a printable representation for the receiver.
1091     */
1092    @Override
1093    public String toString() {
1094        return "Thread[" + name + "," + priority + "," + group.getName() + "]";
1095    }
1096
1097    /**
1098     * Causes the calling Thread to yield execution time to another Thread that
1099     * is ready to run. The actual scheduling is implementation-dependent.
1100     */
1101    public static native void yield();
1102
1103    /**
1104     * Indicates whether the current Thread has a monitor lock on the specified
1105     * object.
1106     *
1107     * @param object the object to test for the monitor lock
1108     * @return true if the current thread has a monitor lock on the specified
1109     *         object; false otherwise
1110     */
1111    public static boolean holdsLock(Object object) {
1112        return currentThread().nativeHoldsLock(object);
1113    }
1114
1115    private native boolean nativeHoldsLock(Object object);
1116
1117    /**
1118     * Implemented by objects that want to handle cases where a thread is being
1119     * terminated by an uncaught exception. Upon such termination, the handler
1120     * is notified of the terminating thread and causal exception. If there is
1121     * no explicit handler set then the thread's group is the default handler.
1122     */
1123    public static interface UncaughtExceptionHandler {
1124        /**
1125         * The thread is being terminated by an uncaught exception. Further
1126         * exceptions thrown in this method are prevent the remainder of the
1127         * method from executing, but are otherwise ignored.
1128         *
1129         * @param thread the thread that has an uncaught exception
1130         * @param ex the exception that was thrown
1131         */
1132        void uncaughtException(Thread thread, Throwable ex);
1133    }
1134
1135    /**
1136     * Unparks this thread. This unblocks the thread it if it was
1137     * previously parked, or indicates that the thread is "preemptively
1138     * unparked" if it wasn't already parked. The latter means that the
1139     * next time the thread is told to park, it will merely clear its
1140     * latent park bit and carry on without blocking.
1141     *
1142     * <p>See {@link java.util.concurrent.locks.LockSupport} for more
1143     * in-depth information of the behavior of this method.</p>
1144     *
1145     * @hide for Unsafe
1146     */
1147    public void unpark() {
1148        synchronized (lock) {
1149            switch (parkState) {
1150                case ParkState.PREEMPTIVELY_UNPARKED: {
1151                    /*
1152                     * Nothing to do in this case: By definition, a
1153                     * preemptively unparked thread is to remain in
1154                     * the preemptively unparked state if it is told
1155                     * to unpark.
1156                     */
1157                    break;
1158                }
1159                case ParkState.UNPARKED: {
1160                    parkState = ParkState.PREEMPTIVELY_UNPARKED;
1161                    break;
1162                }
1163                default /*parked*/: {
1164                    parkState = ParkState.UNPARKED;
1165                    lock.notifyAll();
1166                    break;
1167                }
1168            }
1169        }
1170    }
1171
1172    /**
1173     * Parks the current thread for a particular number of nanoseconds, or
1174     * indefinitely. If not indefinitely, this method unparks the thread
1175     * after the given number of nanoseconds if no other thread unparks it
1176     * first. If the thread has been "preemptively unparked," this method
1177     * cancels that unparking and returns immediately. This method may
1178     * also return spuriously (that is, without the thread being told to
1179     * unpark and without the indicated amount of time elapsing).
1180     *
1181     * <p>See {@link java.util.concurrent.locks.LockSupport} for more
1182     * in-depth information of the behavior of this method.</p>
1183     *
1184     * <p>This method must only be called when <code>this</code> is the current
1185     * thread.
1186     *
1187     * @param nanos number of nanoseconds to park for or <code>0</code>
1188     * to park indefinitely
1189     * @throws IllegalArgumentException thrown if <code>nanos &lt; 0</code>
1190     *
1191     * @hide for Unsafe
1192     */
1193    public void parkFor(long nanos) {
1194        synchronized (lock) {
1195            switch (parkState) {
1196                case ParkState.PREEMPTIVELY_UNPARKED: {
1197                    parkState = ParkState.UNPARKED;
1198                    break;
1199                }
1200                case ParkState.UNPARKED: {
1201                    long millis = nanos / NANOS_PER_MILLI;
1202                    nanos %= NANOS_PER_MILLI;
1203
1204                    parkState = ParkState.PARKED;
1205                    try {
1206                        lock.wait(millis, (int) nanos);
1207                    } catch (InterruptedException ex) {
1208                        interrupt();
1209                    } finally {
1210                        /*
1211                         * Note: If parkState manages to become
1212                         * PREEMPTIVELY_UNPARKED before hitting this
1213                         * code, it should left in that state.
1214                         */
1215                        if (parkState == ParkState.PARKED) {
1216                            parkState = ParkState.UNPARKED;
1217                        }
1218                    }
1219                    break;
1220                }
1221                default /*parked*/: {
1222                    throw new AssertionError("Attempt to repark");
1223                }
1224            }
1225        }
1226    }
1227
1228    /**
1229     * Parks the current thread until the specified system time. This
1230     * method attempts to unpark the current thread immediately after
1231     * <code>System.currentTimeMillis()</code> reaches the specified
1232     * value, if no other thread unparks it first. If the thread has
1233     * been "preemptively unparked," this method cancels that
1234     * unparking and returns immediately. This method may also return
1235     * spuriously (that is, without the thread being told to unpark
1236     * and without the indicated amount of time elapsing).
1237     *
1238     * <p>See {@link java.util.concurrent.locks.LockSupport} for more
1239     * in-depth information of the behavior of this method.</p>
1240     *
1241     * <p>This method must only be called when <code>this</code> is the
1242     * current thread.
1243     *
1244     * @param time the time after which the thread should be unparked,
1245     * in absolute milliseconds-since-the-epoch
1246     *
1247     * @hide for Unsafe
1248     */
1249    public void parkUntil(long time) {
1250        synchronized (lock) {
1251            /*
1252             * Note: This conflates the two time bases of "wall clock"
1253             * time and "monotonic uptime" time. However, given that
1254             * the underlying system can only wait on monotonic time,
1255             * it is unclear if there is any way to avoid the
1256             * conflation. The downside here is that if, having
1257             * calculated the delay, the wall clock gets moved ahead,
1258             * this method may not return until well after the wall
1259             * clock has reached the originally designated time. The
1260             * reverse problem (the wall clock being turned back)
1261             * isn't a big deal, since this method is allowed to
1262             * spuriously return for any reason, and this situation
1263             * can safely be construed as just such a spurious return.
1264             */
1265            long delayMillis = time - System.currentTimeMillis();
1266
1267            if (delayMillis <= 0) {
1268                parkState = ParkState.UNPARKED;
1269            } else {
1270                parkFor(delayMillis * NANOS_PER_MILLI);
1271            }
1272        }
1273    }
1274}
1275