ThreadTest.java revision f6c387128427e121477c1b32ad35cdcaa5101ba3
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
18package org.apache.harmony.luni.tests.java.lang;
19
20import java.io.ByteArrayOutputStream;
21import java.io.PrintStream;
22import java.lang.Thread.UncaughtExceptionHandler;
23import java.security.Permission;
24import java.util.Map;
25
26import dalvik.annotation.AndroidOnly;
27import dalvik.annotation.TestTargets;
28import dalvik.annotation.TestLevel;
29import dalvik.annotation.TestTargetNew;
30import dalvik.annotation.TestTargetClass;
31
32import java.util.concurrent.Semaphore;
33
34@TestTargetClass(Thread.class)
35public class ThreadTest extends junit.framework.TestCase {
36
37    int counter = 0;
38
39    static class SimpleThread implements Runnable {
40        int delay;
41
42        public void run() {
43            try {
44                synchronized (this) {
45                    this.notify();
46                    this.wait(delay);
47                }
48            } catch (InterruptedException e) {
49                return;
50            }
51
52        }
53
54        public SimpleThread(int d) {
55            if (d >= 0)
56                delay = d;
57        }
58    }
59
60    static class YieldThread implements Runnable {
61        volatile int delay;
62
63        public void run() {
64            int x = 0;
65            while (true) {
66                ++x;
67            }
68        }
69
70        public YieldThread(int d) {
71            if (d >= 0)
72                delay = d;
73        }
74    }
75
76    static class ResSupThread implements Runnable {
77        Thread parent;
78
79        volatile int checkVal = -1;
80
81        public void run() {
82            try {
83                synchronized (this) {
84                    this.notify();
85                }
86                while (true) {
87                    checkVal++;
88                    zz();
89                    Thread.sleep(100);
90                }
91            } catch (InterruptedException e) {
92                return;
93            } catch (BogusException e) {
94                try {
95                    // Give parent a chance to sleep
96                    Thread.sleep(500);
97                } catch (InterruptedException x) {
98                }
99                parent.interrupt();
100                while (!Thread.currentThread().isInterrupted()) {
101                    // Don't hog the CPU
102                    try {
103                        Thread.sleep(50);
104                    } catch (InterruptedException x) {
105                        // This is what we've been waiting for...don't throw it
106                        // away!
107                        break;
108                    }
109                }
110            }
111        }
112
113        public void zz() throws BogusException {
114        }
115
116        public ResSupThread(Thread t) {
117            parent = t;
118        }
119
120        public synchronized int getCheckVal() {
121            return checkVal;
122        }
123    }
124
125    static class BogusException extends Throwable {
126
127        private static final long serialVersionUID = 1L;
128
129        public BogusException(String s) {
130            super(s);
131        }
132    }
133
134    // TODO android-added
135    class MonitoredClass {
136        public synchronized void enterLocked() {
137            boolean b = Thread.holdsLock(this);
138            assertTrue("Thread should hold lock for object", b);
139        }
140
141        public void enterNonLocked() {
142            boolean b = Thread.holdsLock(this);
143            assertFalse("Thread should not hold lock for object", b);
144        }
145    }
146
147    Thread st, ct, spinner;
148
149    static boolean calledMySecurityManager = false;
150
151    /**
152     * @tests java.lang.Thread#Thread()
153     */
154    @TestTargetNew(
155        level = TestLevel.COMPLETE,
156        notes = "",
157        method = "Thread",
158        args = {}
159    )
160    public void test_Constructor() {
161        // Test for method java.lang.Thread()
162
163        Thread t;
164        SecurityManager m = new SecurityManager() {
165            @Override
166            public ThreadGroup getThreadGroup() {
167                calledMySecurityManager = true;
168                return Thread.currentThread().getThreadGroup();
169            }
170
171            @Override
172            public void checkPermission(Permission permission) {
173                if (permission.getName().equals("setSecurityManager")) {
174                    return;
175                }
176                super.checkPermission(permission);
177            }
178        };
179        try {
180            // To see if it checks Thread creation with our SecurityManager
181            System.setSecurityManager(m);
182            t = new Thread();
183        } finally {
184            // restore original, no side-effects
185            System.setSecurityManager(null);
186        }
187        assertTrue("Did not call SecurityManager.getThreadGroup ()",
188                calledMySecurityManager);
189        t.start();
190    }
191
192    /**
193     * @tests java.lang.Thread#Thread(java.lang.Runnable)
194     */
195    @TestTargetNew(
196        level = TestLevel.COMPLETE,
197        notes = "",
198        method = "Thread",
199        args = {java.lang.Runnable.class}
200    )
201    public void test_ConstructorLjava_lang_Runnable() {
202        // Test for method java.lang.Thread(java.lang.Runnable)
203        try {
204            ct = new Thread(new SimpleThread(10));
205            ct.start();
206        } catch (Exception e) {
207            fail("Failed to create subthread : " + e.getMessage());
208        }
209    }
210
211    /**
212     * @tests java.lang.Thread#Thread(java.lang.Runnable, java.lang.String)
213     */
214    @TestTargetNew(
215        level = TestLevel.COMPLETE,
216        notes = "",
217        method = "Thread",
218        args = {java.lang.Runnable.class, java.lang.String.class}
219    )
220    public void test_ConstructorLjava_lang_RunnableLjava_lang_String() {
221        // Test for method java.lang.Thread(java.lang.Runnable,
222        // java.lang.String)
223        Thread st1 = new Thread(new SimpleThread(1), "SimpleThread1");
224        assertEquals("Constructed thread with incorrect thread name", "SimpleThread1", st1
225                .getName());
226        st1.start();
227    }
228
229    /**
230     * @tests java.lang.Thread#Thread(java.lang.String)
231     */
232    @TestTargetNew(
233        level = TestLevel.COMPLETE,
234        notes = "",
235        method = "Thread",
236        args = {java.lang.String.class}
237    )
238    public void test_ConstructorLjava_lang_String() {
239        // Test for method java.lang.Thread(java.lang.String)
240        Thread t = new Thread("Testing");
241        assertEquals("Created tread with incorrect name",
242                "Testing", t.getName());
243        t.start();
244    }
245
246    /**
247     * @tests java.lang.Thread#Thread(java.lang.ThreadGroup, java.lang.Runnable)
248     */
249    @TestTargetNew(
250        level = TestLevel.COMPLETE,
251        notes = "",
252        method = "Thread",
253        args = {java.lang.ThreadGroup.class, java.lang.Runnable.class}
254    )
255    public void test_ConstructorLjava_lang_ThreadGroupLjava_lang_Runnable() {
256        // Test for method java.lang.Thread(java.lang.ThreadGroup,
257        // java.lang.Runnable)
258        ThreadGroup tg = new ThreadGroup("Test Group1");
259        st = new Thread(tg, new SimpleThread(1), "SimpleThread2");
260        assertTrue("Returned incorrect thread group", st.getThreadGroup() == tg);
261        st.start();
262        try {
263            st.join();
264        } catch (InterruptedException e) {
265        }
266        tg.destroy();
267    }
268
269    /**
270     * @tests java.lang.Thread#Thread(java.lang.ThreadGroup, java.lang.Runnable,
271     *        java.lang.String)lo
272     */
273    @TestTargetNew(
274        level = TestLevel.COMPLETE,
275        notes = "",
276        method = "Thread",
277        args = {java.lang.ThreadGroup.class, java.lang.Runnable.class, java.lang.String.class}
278    )
279    public void test_ConstructorLjava_lang_ThreadGroupLjava_lang_RunnableLjava_lang_String() {
280        // Test for method java.lang.Thread(java.lang.ThreadGroup,
281        // java.lang.Runnable, java.lang.String)
282        ThreadGroup tg = new ThreadGroup("Test Group2");
283        st = new Thread(tg, new SimpleThread(1), "SimpleThread3");
284        assertTrue("Constructed incorrect thread", (st.getThreadGroup() == tg)
285                && st.getName().equals("SimpleThread3"));
286        st.start();
287        try {
288            st.join();
289        } catch (InterruptedException e) {
290        }
291        tg.destroy();
292
293        Runnable r = new Runnable() {
294            public void run() {
295            }
296        };
297
298        ThreadGroup foo = null;
299        try {
300            new Thread(foo = new ThreadGroup("foo"), r, null);
301            // Should not get here
302            fail("Null cannot be accepted as Thread name");
303        } catch (NullPointerException npe) {
304            assertTrue("Null cannot be accepted as Thread name", true);
305            foo.destroy();
306        }
307    }
308
309    @TestTargetNew(
310        level = TestLevel.COMPLETE,
311        notes = "",
312        method = "Thread",
313        args = {java.lang.ThreadGroup.class, java.lang.Runnable.class, java.lang.String.class, long.class}
314    )
315    public void test_ConstructorLjava_lang_ThreadGroupLjava_lang_RunnableLjava_lang_StringL$L() {
316        ThreadGroup tg = new ThreadGroup("Test Group2");
317        st = new Thread(tg, new SimpleThread(1), "SimpleThread3", 1);
318        assertTrue("Constructed incorrect thread", (st.getThreadGroup() == tg)
319                && st.getName().equals("SimpleThread3"));
320        st.start();
321        try {
322            st.join();
323        } catch (InterruptedException e) {
324        }
325        tg.destroy();
326
327        Runnable r = new Runnable() {
328            public void run() {
329            }
330        };
331
332        try {
333            new Thread(tg, new SimpleThread(1), "SimpleThread3",
334                    Integer.MAX_VALUE);
335            fail("StackOverflowError/OutOfMemoryError is not thrown.");
336        } catch(IllegalThreadStateException itse) {
337            //expected
338        }
339
340    }
341
342    /**
343     * @tests java.lang.Thread#Thread(java.lang.ThreadGroup, java.lang.String)
344     */
345    @TestTargetNew(
346        level = TestLevel.COMPLETE,
347        notes = "",
348        method = "Thread",
349        args = {java.lang.ThreadGroup.class, java.lang.String.class}
350    )
351    public void test_ConstructorLjava_lang_ThreadGroupLjava_lang_String() {
352        // Test for method java.lang.Thread(java.lang.ThreadGroup,
353        // java.lang.String)
354        st = new Thread(new SimpleThread(1), "SimpleThread4");
355        assertEquals("Returned incorrect thread name",
356                "SimpleThread4", st.getName());
357        st.start();
358    }
359
360    /**
361     * @tests java.lang.Thread#activeCount()
362     */
363    @TestTargetNew(
364        level = TestLevel.COMPLETE,
365        notes = "",
366        method = "activeCount",
367        args = {}
368    )
369    public void test_activeCount() {
370        // Test for method int java.lang.Thread.activeCount()
371        Thread t = new Thread(new SimpleThread(1));
372        int active = Thread.activeCount();
373        assertTrue("Incorrect read made: " + active, active > 0);
374        t.start();
375        try {
376            t.join();
377        } catch (InterruptedException e) {
378        }
379    }
380
381    /**
382     * @tests java.lang.Thread#checkAccess()
383     */
384    @TestTargetNew(
385        level = TestLevel.COMPLETE,
386        notes = "",
387        method = "checkAccess",
388        args = {}
389    )
390    public void test_checkAccess() {
391        // Test for method void java.lang.Thread.checkAccess()
392        ThreadGroup tg = new ThreadGroup("Test Group3");
393        try {
394            st = new Thread(tg, new SimpleThread(1), "SimpleThread5");
395            st.checkAccess();
396            assertTrue("CheckAccess passed", true);
397        } catch (SecurityException e) {
398            fail("CheckAccess failed : " + e.getMessage());
399        }
400        st.start();
401        try {
402            st.join();
403        } catch (InterruptedException e) {
404        }
405        tg.destroy();
406
407        SecurityManager sm = new SecurityManager() {
408
409            public void checkPermission(Permission perm) {
410            }
411
412            public void checkAccess(Thread t) {
413               throw new SecurityException();
414            }
415        };
416
417        SecurityManager oldSm = System.getSecurityManager();
418        System.setSecurityManager(sm);
419        try {
420            st.checkAccess();
421            fail("Should throw SecurityException");
422        } catch (SecurityException e) {
423            // expected
424        } finally {
425           System.setSecurityManager(oldSm);
426        }
427    }
428
429    /**
430     * @tests java.lang.Thread#countStackFrames()
431     */
432    @TestTargetNew(
433        level = TestLevel.COMPLETE,
434        notes = "",
435        method = "countStackFrames",
436        args = {}
437    )
438    @SuppressWarnings("deprecation")
439    public void test_countStackFrames() {
440        /*
441         * Thread.countStackFrames() is unpredictable, so we just test that it
442         * doesn't throw an exception.
443         */
444        try {
445            Thread.currentThread().countStackFrames();
446        } catch (Throwable t) {
447            fail("unexpected throwable: " + t.toString());
448        }
449    }
450
451    /**
452     * @tests java.lang.Thread#currentThread()
453     */
454    @TestTargetNew(
455        level = TestLevel.COMPLETE,
456        notes = "",
457        method = "currentThread",
458        args = {}
459    )
460    public void test_currentThread() {
461        assertNotNull(Thread.currentThread());
462    }
463
464    /**
465     * @tests java.lang.Thread#destroy()
466     */
467    @TestTargetNew(
468        level = TestLevel.COMPLETE,
469        notes = "",
470        method = "destroy",
471        args = {}
472    )
473    @SuppressWarnings("deprecation")
474    public void test_destroy() {
475        try {
476            new Thread().destroy();
477            // FIXME uncomment when IBM VME is updated
478            fail("NoSuchMethodError was not thrown");
479        } catch (NoSuchMethodError e) {
480        }
481    }
482
483    @TestTargetNew(
484        level = TestLevel.COMPLETE,
485        notes = "",
486        method = "dumpStack",
487        args = {}
488    )
489    public void test_dumpStack() {
490        try {
491            PrintStream savedErr = System.err;
492            ByteArrayOutputStream baos = new ByteArrayOutputStream();
493            System.setErr(new PrintStream(baos));
494            Thread.dumpStack();
495            System.setErr(savedErr);
496
497            String s = new String(baos.toByteArray());
498
499            assertTrue(s.contains("java.lang.Thread.dumpStack"));
500
501        } catch(Exception e) {
502            fail("Unexpected exception was thrown: " + e.toString());
503        }
504    }
505
506    /**
507     * @tests java.lang.Thread#enumerate(java.lang.Thread[])
508     */
509    @TestTargetNew(
510        level = TestLevel.COMPLETE,
511        notes = "",
512        method = "enumerate",
513        args = {java.lang.Thread[].class}
514    )
515    public void test_enumerate$Ljava_lang_Thread() {
516        // Test for method int java.lang.Thread.enumerate(java.lang.Thread [])
517        // The test has been updated according to HARMONY-1974 JIRA issue.
518
519        class MyThread extends Thread {
520            MyThread(ThreadGroup tg, String name) {
521                super(tg, name);
522            }
523
524            boolean failed = false;
525            String failMessage = null;
526
527            public void run() {
528                SimpleThread st1 = null;
529                SimpleThread st2 = null;
530                ThreadGroup mytg = null;
531                Thread firstOne = null;
532                Thread secondOne = null;
533                try {
534                    int arrayLength = 10;
535                    Thread[] tarray = new Thread[arrayLength];
536                    st1 = new SimpleThread(-1);
537                    st2 = new SimpleThread(-1);
538                    mytg = new ThreadGroup("jp");
539                    firstOne = new Thread(mytg, st1, "firstOne2");
540                    secondOne = new Thread(mytg, st2, "secondOne1");
541                    int count = Thread.enumerate(tarray);
542                    assertEquals("Incorrect value returned1",
543                            1, count);
544                    synchronized (st1) {
545                        firstOne.start();
546                        try {
547                            st1.wait();
548                        } catch (InterruptedException e) {
549                        }
550                    }
551                    count = Thread.enumerate(tarray);
552                    assertEquals("Incorrect value returned2",
553                            2, count);
554                    synchronized (st2) {
555                        secondOne.start();
556                        try {
557                            st2.wait();
558                        } catch (InterruptedException e) {
559                        }
560                    }
561                    count = Thread.enumerate(tarray);
562                    assertEquals("Incorrect value returned3",
563                            3, count);
564                } catch (junit.framework.AssertionFailedError e) {
565                    failed = true;
566                    failMessage = e.getMessage();
567                } finally {
568                    synchronized (st1) {
569                        firstOne.interrupt();
570                    }
571                    synchronized (st2) {
572                        secondOne.interrupt();
573                    }
574                    try {
575                        firstOne.join();
576                        secondOne.join();
577                    } catch (InterruptedException e) {
578                    }
579                    mytg.destroy();
580                }
581            }
582        };
583
584        ThreadGroup tg = new ThreadGroup("tg");
585        MyThread t = new MyThread(tg, "top");
586        t.start();
587        try {
588            t.join();
589        } catch (InterruptedException e) {
590            fail("Unexpected interrupt");
591        } finally {
592            tg.destroy();
593        }
594        assertFalse(t.failMessage, t.failed);
595    }
596
597    /**
598     * @tests java.lang.Thread#getContextClassLoader()
599     */
600    @TestTargetNew(
601        level = TestLevel.COMPLETE,
602        notes = "",
603        method = "getContextClassLoader",
604        args = {}
605    )
606    public void test_getContextClassLoader() {
607        // Test for method java.lang.ClassLoader
608        // java.lang.Thread.getContextClassLoader()
609        Thread t = new Thread();
610        assertTrue("Incorrect class loader returned",
611                t.getContextClassLoader() == Thread.currentThread()
612                        .getContextClassLoader());
613        t.start();
614
615 /*       SecurityManager sm = new SecurityManager() {
616
617            public void checkPermission(Permission perm) {
618                if(perm.getName().equals("getClassLoader")) {
619                    throw new SecurityException();
620                }
621            }
622        };
623
624        SecurityManager oldSm = System.getSecurityManager();
625        System.setSecurityManager(sm);
626        try {
627            t.getContextClassLoader();
628            fail("Should throw SecurityException");
629        } catch (SecurityException e) {
630            // expected
631        } finally {
632           System.setSecurityManager(oldSm);
633        }
634*/
635    }
636
637    /**
638     * @tests java.lang.Thread#getName()
639     */
640    @TestTargetNew(
641        level = TestLevel.COMPLETE,
642        notes = "",
643        method = "getName",
644        args = {}
645    )
646    public void test_getName() {
647        // Test for method java.lang.String java.lang.Thread.getName()
648        st = new Thread(new SimpleThread(1), "SimpleThread6");
649        assertEquals("Returned incorrect thread name",
650                "SimpleThread6", st.getName());
651        st.start();
652    }
653
654    /**
655     * @tests java.lang.Thread#getPriority()
656     */
657    @TestTargetNew(
658        level = TestLevel.COMPLETE,
659        notes = "",
660        method = "getPriority",
661        args = {}
662    )
663    public void test_getPriority() {
664        // Test for method int java.lang.Thread.getPriority()
665        st = new Thread(new SimpleThread(1));
666        st.setPriority(Thread.MAX_PRIORITY);
667        assertTrue("Returned incorrect thread priority",
668                st.getPriority() == Thread.MAX_PRIORITY);
669        st.start();
670    }
671
672    /**
673     * @tests java.lang.Thread#getThreadGroup()
674     */
675    @TestTargetNew(
676        level = TestLevel.COMPLETE,
677        notes = "",
678        method = "getThreadGroup",
679        args = {}
680    )
681    public void test_getThreadGroup() {
682        // Test for method java.lang.ThreadGroup
683        // java.lang.Thread.getThreadGroup()
684        ThreadGroup tg = new ThreadGroup("Test Group4");
685        st = new Thread(tg, /* new SimpleThread(1), */ "SimpleThread8");
686        assertTrue("Returned incorrect thread group", st.getThreadGroup() == tg);
687        st.start();
688        try {
689            st.join();
690        } catch (InterruptedException e) {
691        }
692        assertNull("group should be null", st.getThreadGroup());
693        assertNotNull("toString() should not be null", st.toString());
694        tg.destroy();
695
696        final Object lock = new Object();
697        Thread t = new Thread() {
698            @Override
699            public void run() {
700                synchronized (lock) {
701                    lock.notifyAll();
702                }
703            }
704        };
705        synchronized (lock) {
706            t.start();
707            try {
708                lock.wait();
709            } catch (InterruptedException e) {
710            }
711        }
712        int running = 0;
713        while (t.isAlive())
714            running++;
715        ThreadGroup group = t.getThreadGroup();
716        assertNull("ThreadGroup is not null", group);
717    }
718
719    /**
720     * @tests java.lang.Thread#interrupt()
721     */
722    @TestTargetNew(
723        level = TestLevel.COMPLETE,
724        notes = "",
725        method = "interrupt",
726        args = {}
727    )
728    public void test_interrupt() {
729        // Test for method void java.lang.Thread.interrupt()
730        final Object lock = new Object();
731        class ChildThread1 extends Thread {
732            Thread parent;
733
734            boolean sync;
735
736            @Override
737            public void run() {
738                if (sync) {
739                    synchronized (lock) {
740                        lock.notify();
741                        try {
742                            lock.wait();
743                        } catch (InterruptedException e) {
744                        }
745                    }
746                }
747                parent.interrupt();
748            }
749
750            public ChildThread1(Thread p, String name, boolean sync) {
751                super(name);
752                parent = p;
753                this.sync = sync;
754            }
755        }
756        boolean interrupted = false;
757        try {
758            ct = new ChildThread1(Thread.currentThread(), "Interrupt Test1",
759                    false);
760            synchronized (lock) {
761                ct.start();
762                lock.wait();
763            }
764        } catch (InterruptedException e) {
765            interrupted = true;
766        }
767        assertTrue("Failed to Interrupt thread1", interrupted);
768
769        interrupted = false;
770        try {
771            ct = new ChildThread1(Thread.currentThread(), "Interrupt Test2",
772                    true);
773            synchronized (lock) {
774                ct.start();
775                lock.wait();
776                lock.notify();
777            }
778            Thread.sleep(20000);
779        } catch (InterruptedException e) {
780            interrupted = true;
781        }
782        assertTrue("Failed to Interrupt thread2", interrupted);
783
784        SecurityManager sm = new SecurityManager() {
785
786            public void checkPermission(Permission perm) {
787            }
788
789            public void checkAccess(Thread t) {
790               throw new SecurityException();
791            }
792        };
793        st = new Thread();
794        SecurityManager oldSm = System.getSecurityManager();
795        System.setSecurityManager(sm);
796        try {
797            st.interrupt();
798            fail("Should throw SecurityException");
799        } catch (SecurityException e) {
800            // expected
801        } finally {
802           System.setSecurityManager(oldSm);
803        }
804    }
805
806    /**
807     * @tests java.lang.Thread#interrupted()
808     */
809    @TestTargetNew(
810        level = TestLevel.COMPLETE,
811        notes = "",
812        method = "interrupted",
813        args = {}
814    )
815    public void test_interrupted() {
816        assertFalse("Interrupted returned true for non-interrupted thread", Thread
817                .interrupted());
818        Thread.currentThread().interrupt();
819        assertTrue("Interrupted returned true for non-interrupted thread", Thread.interrupted());
820        assertFalse("Failed to clear interrupted flag", Thread.interrupted());
821    }
822
823    /**
824     * @tests java.lang.Thread#isAlive()
825     */
826    @TestTargetNew(
827        level = TestLevel.COMPLETE,
828        notes = "",
829        method = "isAlive",
830        args = {}
831    )
832    public void test_isAlive() {
833        // Test for method boolean java.lang.Thread.isAlive()
834        SimpleThread simple;
835        st = new Thread(simple = new SimpleThread(500));
836        assertFalse("A thread that wasn't started is alive.", st.isAlive());
837        synchronized (simple) {
838            st.start();
839            try {
840                simple.wait();
841            } catch (InterruptedException e) {
842            }
843        }
844        assertTrue("Started thread returned false", st.isAlive());
845
846        try {
847            st.join();
848        } catch (InterruptedException e) {
849            fail("Thread did not die");
850        }
851        assertTrue("Stopped thread returned true", !st.isAlive());
852    }
853
854    /**
855     * @tests java.lang.Thread#isDaemon()
856     */
857    @TestTargetNew(
858        level = TestLevel.COMPLETE,
859        notes = "",
860        method = "isDaemon",
861        args = {}
862    )
863    public void test_isDaemon() {
864        // Test for method boolean java.lang.Thread.isDaemon()
865        st = new Thread(new SimpleThread(1), "SimpleThread10");
866        assertTrue("Non-Daemon thread returned true", !st.isDaemon());
867        st.setDaemon(true);
868        assertTrue("Daemon thread returned false", st.isDaemon());
869        st.start();
870    }
871
872    /**
873     * @tests java.lang.Thread#isInterrupted()
874     */
875    @TestTargetNew(
876        level = TestLevel.COMPLETE,
877        notes = "",
878        method = "isInterrupted",
879        args = {}
880    )
881    public void test_isInterrupted() {
882        // Test for method boolean java.lang.Thread.isInterrupted()
883        class SpinThread implements Runnable {
884            public volatile boolean done = false;
885
886            public void run() {
887                while (!Thread.currentThread().isInterrupted())
888                    ;
889                while (!done)
890                    ;
891            }
892        }
893
894        SpinThread spin = new SpinThread();
895        spinner = new Thread(spin);
896        spinner.start();
897        Thread.yield();
898        try {
899            assertTrue("Non-Interrupted thread returned true", !spinner
900                    .isInterrupted());
901            spinner.interrupt();
902            assertTrue("Interrupted thread returned false", spinner
903                    .isInterrupted());
904            spin.done = true;
905        } finally {
906            spinner.interrupt();
907            spin.done = true;
908        }
909    }
910
911    /**
912     * @tests java.lang.Thread#join()
913     */
914    @TestTargetNew(
915        level = TestLevel.COMPLETE,
916        notes = "",
917        method = "join",
918        args = {}
919    )
920    public void test_join() {
921        // Test for method void java.lang.Thread.join()
922        SimpleThread simple;
923        try {
924            st = new Thread(simple = new SimpleThread(100));
925            // cause isAlive() to be compiled by the JIT, as it must be called
926            // within 100ms below.
927            assertTrue("Thread is alive", !st.isAlive());
928            synchronized (simple) {
929                st.start();
930                simple.wait();
931            }
932            st.join();
933        } catch (InterruptedException e) {
934            fail("Join failed ");
935        }
936        assertTrue("Joined thread is still alive", !st.isAlive());
937        boolean result = true;
938        Thread th = new Thread("test");
939        try {
940            th.join();
941        } catch (InterruptedException e) {
942            result = false;
943        }
944        assertTrue("Hung joining a non-started thread", result);
945        th.start();
946
947        st = new Thread() {
948            public void run() {
949                try {
950                    join();
951                    fail("InterruptedException was not thrown.");
952                } catch(InterruptedException ie) {
953                    //expected
954                }
955            }
956        };
957
958        st.start();
959    }
960
961    /**
962     * @tests java.lang.Thread#join(long)
963     */
964    @TestTargetNew(
965        level = TestLevel.COMPLETE,
966        notes = "",
967        method = "join",
968        args = {long.class}
969    )
970    public void test_joinJ() {
971        // Test for method void java.lang.Thread.join(long)
972        SimpleThread simple;
973        try {
974            st = new Thread(simple = new SimpleThread(1000), "SimpleThread12");
975            // cause isAlive() to be compiled by the JIT, as it must be called
976            // within 100ms below.
977            assertTrue("Thread is alive", !st.isAlive());
978            synchronized (simple) {
979                st.start();
980                simple.wait();
981            }
982            st.join(10);
983        } catch (InterruptedException e) {
984            fail("Join failed ");
985        }
986        assertTrue("Join failed to timeout", st.isAlive());
987
988        st.interrupt();
989        try {
990            st = new Thread(simple = new SimpleThread(100), "SimpleThread13");
991            synchronized (simple) {
992                st.start();
993                simple.wait();
994            }
995            st.join(1000);
996        } catch (InterruptedException e) {
997            fail("Join failed : " + e.getMessage());
998            return;
999        }
1000        assertTrue("Joined thread is still alive", !st.isAlive());
1001
1002        final Object lock = new Object();
1003        final Thread main = Thread.currentThread();
1004        Thread killer = new Thread(new Runnable() {
1005            public void run() {
1006                try {
1007                    synchronized (lock) {
1008                        lock.notify();
1009                    }
1010                    Thread.sleep(100);
1011                } catch (InterruptedException e) {
1012                    return;
1013                }
1014                main.interrupt();
1015            }
1016        });
1017        boolean result = true;
1018        Thread th = new Thread("test");
1019        try {
1020            synchronized (lock) {
1021                killer.start();
1022                lock.wait();
1023            }
1024            th.join(200);
1025        } catch (InterruptedException e) {
1026            result = false;
1027        }
1028        killer.interrupt();
1029        assertTrue("Hung joining a non-started thread", result);
1030        th.start();
1031
1032        st = new Thread() {
1033            public void run() {
1034                try {
1035                    join(1000);
1036                    fail("InterruptedException was not thrown.");
1037                } catch(InterruptedException ie) {
1038                    //expected
1039                }
1040            }
1041        };
1042
1043        st.start();
1044    }
1045
1046    /**
1047     * @tests java.lang.Thread#join(long, int)
1048     */
1049    @TestTargetNew(
1050        level = TestLevel.COMPLETE,
1051        notes = "",
1052        method = "join",
1053        args = {long.class, int.class}
1054    )
1055    public void test_joinJI() {
1056        // Test for method void java.lang.Thread.join(long, int)
1057        SimpleThread simple;
1058        try {
1059            st = new Thread(simple = new SimpleThread(1000), "Squawk1");
1060            assertTrue("Thread is alive", !st.isAlive());
1061            synchronized (simple) {
1062                st.start();
1063                simple.wait();
1064            }
1065
1066            long firstRead = System.currentTimeMillis();
1067            st.join(100, 999999);
1068            long secondRead = System.currentTimeMillis();
1069            assertTrue("Did not join by appropriate time: " + secondRead + "-"
1070                    + firstRead + "=" + (secondRead - firstRead), secondRead
1071                    - firstRead <= 300);
1072            assertTrue("Joined thread is not alive", st.isAlive());
1073            st.interrupt();
1074        } catch (Exception e) {
1075            fail("Exception during test : " + e.getMessage());
1076        }
1077
1078        final Object lock = new Object();
1079        final Thread main = Thread.currentThread();
1080        Thread killer = new Thread(new Runnable() {
1081            public void run() {
1082                try {
1083                    synchronized (lock) {
1084                        lock.notify();
1085                    }
1086                    Thread.sleep(100);
1087                } catch (InterruptedException e) {
1088                    return;
1089                }
1090                main.interrupt();
1091            }
1092        });
1093        boolean result = true;
1094        Thread th = new Thread("test");
1095        try {
1096            synchronized (lock) {
1097                killer.start();
1098                lock.wait();
1099            }
1100            th.join(200, 20);
1101        } catch (InterruptedException e) {
1102            result = false;
1103        }
1104        killer.interrupt();
1105        assertTrue("Hung joining a non-started thread", result);
1106        th.start();
1107
1108        st = new Thread() {
1109            public void run() {
1110                try {
1111                    join(1000, 20);
1112                    fail("InterruptedException was not thrown.");
1113                } catch(InterruptedException ie) {
1114                    //expected
1115                }
1116            }
1117        };
1118
1119        st.start();
1120    }
1121
1122    @TestTargets({
1123        @TestTargetNew(
1124            level = TestLevel.COMPLETE,
1125            notes = "",
1126            method = "setContextClassLoader",
1127            args = {java.lang.ClassLoader.class}
1128        ),
1129        @TestTargetNew(
1130            level = TestLevel.COMPLETE,
1131            notes = "",
1132            method = "getContextClassLoader",
1133            args = {}
1134        )
1135    })
1136    public void test_setContextClassLoader() {
1137        PublicClassLoader pcl = new PublicClassLoader();
1138        st = new Thread();
1139        st.setContextClassLoader(pcl);
1140        assertEquals(pcl, st.getContextClassLoader());
1141
1142        st.setContextClassLoader(null);
1143        assertNull(st.getContextClassLoader());
1144
1145        SecurityManager sm = new SecurityManager() {
1146            public void checkPermission(Permission perm) {
1147                if (perm.getName().equals("setContextClassLoader")
1148                        || perm.getName().equals("getClassLoader") ) {
1149                    throw new SecurityException();
1150                }
1151            }
1152        };
1153
1154        SecurityManager oldSm = System.getSecurityManager();
1155        System.setSecurityManager(sm);
1156        try {
1157            st.setContextClassLoader(pcl);
1158            fail("Should throw SecurityException");
1159        } catch (SecurityException e) {
1160            // expected
1161        } finally {
1162            System.setSecurityManager(oldSm);
1163        }
1164    }
1165
1166
1167    /**
1168     * @tests java.lang.Thread#resume()
1169     */
1170    @TestTargetNew(
1171        level = TestLevel.COMPLETE,
1172        notes = "",
1173        method = "resume",
1174        args = {}
1175    )
1176    @AndroidOnly("Android throws UnsupportedOperationException for Thread.resume()")
1177    @SuppressWarnings("deprecation")
1178    public void test_resume() {
1179        // Test for method void java.lang.Thread.resume()
1180        int orgval;
1181        ResSupThread t;
1182        try {
1183            t = new ResSupThread(Thread.currentThread());
1184            synchronized (t) {
1185                ct = new Thread(t, "Interrupt Test2");
1186                ct.start();
1187                t.wait();
1188            }
1189            try {
1190                ct.resume();
1191            } catch (UnsupportedOperationException e) {
1192                // expected
1193            }
1194        } catch (InterruptedException e) {
1195            fail("Unexpected interrupt occurred : " + e.getMessage());
1196        }
1197
1198        // Security checks are made even though resume() is not supported.
1199        SecurityManager sm = new SecurityManager() {
1200            public void checkPermission(Permission perm) {
1201            }
1202
1203            public void checkAccess(Thread t) {
1204                throw new SecurityException();
1205            }
1206        };
1207        st = new Thread();
1208        SecurityManager oldSm = System.getSecurityManager();
1209        System.setSecurityManager(sm);
1210        try {
1211            st.resume();
1212            fail("Should throw SecurityException");
1213        } catch (SecurityException e) {
1214            // expected
1215        } finally {
1216            System.setSecurityManager(oldSm);
1217        }
1218    }
1219
1220    /**
1221     * @tests java.lang.Thread#run()
1222     */
1223    @TestTargetNew(
1224        level = TestLevel.COMPLETE,
1225        notes = "",
1226        method = "run",
1227        args = {}
1228    )
1229    public void test_run() {
1230        // Test for method void java.lang.Thread.run()
1231        class RunThread implements Runnable {
1232            boolean didThreadRun = false;
1233
1234            public void run() {
1235                didThreadRun = true;
1236            }
1237        }
1238        RunThread rt = new RunThread();
1239        Thread t = new Thread(rt);
1240        try {
1241            t.start();
1242            int count = 0;
1243            while (!rt.didThreadRun && count < 20) {
1244                Thread.sleep(100);
1245                count++;
1246            }
1247            assertTrue("Thread did not run", rt.didThreadRun);
1248            t.join();
1249        } catch (InterruptedException e) {
1250            assertTrue("Joined thread was interrupted", true);
1251        }
1252        assertTrue("Joined thread is still alive", !t.isAlive());
1253    }
1254
1255    /**
1256     * @tests java.lang.Thread#setDaemon(boolean)
1257     */
1258    @TestTargetNew(
1259        level = TestLevel.COMPLETE,
1260        notes = "",
1261        method = "setDaemon",
1262        args = {boolean.class}
1263    )
1264    public void test_setDaemonZ() {
1265        // Test for method void java.lang.Thread.setDaemon(boolean)
1266        st = new Thread(new SimpleThread(1), "SimpleThread14");
1267        st.setDaemon(true);
1268        assertTrue("Failed to set thread as daemon thread", st.isDaemon());
1269        st.start();
1270
1271        // BEGIN android-added
1272        st = new Thread(new SimpleThread(5));
1273        st.start();
1274        try {
1275            st.setDaemon(false);
1276            fail("setDaemon() must throw exception for started thread");
1277        } catch (IllegalThreadStateException ex) {
1278            // We expect this one.
1279        }
1280        // END android-added
1281
1282        SecurityManager sm = new SecurityManager() {
1283
1284            public void checkPermission(Permission perm) {
1285            }
1286
1287            public void checkAccess(Thread t) {
1288               throw new SecurityException();
1289            }
1290        };
1291
1292        SecurityManager oldSm = System.getSecurityManager();
1293        System.setSecurityManager(sm);
1294        try {
1295            st.setDaemon(false);
1296            fail("Should throw SecurityException");
1297        } catch (SecurityException e) {
1298            // expected
1299        } finally {
1300            System.setSecurityManager(oldSm);
1301        }
1302    }
1303
1304    /**
1305     * @tests java.lang.Thread#setName(java.lang.String)
1306     */
1307    @TestTargetNew(
1308        level = TestLevel.COMPLETE,
1309        notes = "",
1310        method = "setName",
1311        args = {java.lang.String.class}
1312    )
1313    public void test_setNameLjava_lang_String() {
1314        // Test for method void java.lang.Thread.setName(java.lang.String)
1315        st = new Thread(new SimpleThread(1), "SimpleThread15");
1316        st.setName("Bogus Name");
1317        assertEquals("Failed to set thread name",
1318                "Bogus Name", st.getName());
1319        try {
1320            st.setName(null);
1321            fail("Null should not be accepted as a valid name");
1322        } catch (NullPointerException e) {
1323            // success
1324            assertTrue("Null should not be accepted as a valid name", true);
1325        }
1326        st.start();
1327
1328        SecurityManager sm = new SecurityManager() {
1329
1330            public void checkPermission(Permission perm) {
1331            }
1332
1333            public void checkAccess(Thread t) {
1334               throw new SecurityException();
1335            }
1336        };
1337
1338        SecurityManager oldSm = System.getSecurityManager();
1339        System.setSecurityManager(sm);
1340        try {
1341            st.setName("Bogus Name");
1342            fail("Should throw SecurityException");
1343        } catch (SecurityException e) {
1344            // expected
1345        } finally {
1346           System.setSecurityManager(oldSm);
1347        }
1348    }
1349
1350    /**
1351     * @tests java.lang.Thread#setPriority(int)
1352     */
1353    @TestTargetNew(
1354        level = TestLevel.COMPLETE,
1355        notes = "",
1356        method = "setPriority",
1357        args = {int.class}
1358    )
1359    public void test_setPriorityI() {
1360        // Test for method void java.lang.Thread.setPriority(int)
1361        st = new Thread(new SimpleThread(1));
1362        st.setPriority(Thread.MAX_PRIORITY);
1363        assertTrue("Failed to set priority",
1364                st.getPriority() == Thread.MAX_PRIORITY);
1365        st.start();
1366
1367        SecurityManager sm = new SecurityManager() {
1368
1369            public void checkPermission(Permission perm) {
1370            }
1371
1372            public void checkAccess(Thread t) {
1373               throw new SecurityException();
1374            }
1375        };
1376
1377        SecurityManager oldSm = System.getSecurityManager();
1378        System.setSecurityManager(sm);
1379        try {
1380            st.setPriority(Thread.MIN_PRIORITY);
1381            fail("Should throw SecurityException");
1382        } catch (SecurityException e) {
1383            // expected
1384        } finally {
1385            System.setSecurityManager(oldSm);
1386        }
1387
1388        try {
1389            st.setPriority(Thread.MIN_PRIORITY - 1);
1390            fail("IllegalArgumentException is not thrown.");
1391        } catch(IllegalArgumentException iae) {
1392            //expected
1393        }
1394
1395        try {
1396            st.setPriority(Thread.MAX_PRIORITY + 1);
1397            fail("IllegalArgumentException is not thrown.");
1398        } catch(IllegalArgumentException iae) {
1399            //expected
1400        }
1401    }
1402
1403    /**
1404     * @tests java.lang.Thread#sleep(long)
1405     */
1406    @TestTargetNew(
1407        level = TestLevel.COMPLETE,
1408        notes = "",
1409        method = "sleep",
1410        args = {long.class}
1411    )
1412    public void test_sleepJ() {
1413        // Test for method void java.lang.Thread.sleep(long)
1414
1415        // TODO : Test needs enhancing.
1416        long stime = 0, ftime = 0;
1417        try {
1418            stime = System.currentTimeMillis();
1419            Thread.sleep(1000);
1420            ftime = System.currentTimeMillis();
1421        } catch (InterruptedException e) {
1422            fail("Unexpected interrupt received");
1423        }
1424        assertTrue("Failed to sleep long enough", (ftime - stime) >= 800);
1425
1426        counter = 0;
1427        st = new Thread() {
1428
1429            public void run() {
1430                while(true) {
1431                    try {
1432                        sleep(1000);
1433                        counter++;
1434                    } catch(InterruptedException e) {
1435
1436                    }
1437                }
1438            }
1439        };
1440
1441        st.start();
1442
1443        try {
1444            Thread.sleep(5000);
1445        } catch(InterruptedException e) {
1446            fail("InterruptedException was thrown.");
1447        }
1448        assertEquals(4, counter);
1449
1450        st = new Thread() {
1451            public void run() {
1452                try {
1453                    sleep(10000);
1454                    fail("InterruptedException is thrown.");
1455                } catch(InterruptedException ie) {
1456                    //exception
1457                }
1458            }
1459        };
1460
1461        st.start();
1462        st.interrupt();
1463    }
1464
1465    /**
1466     * @tests java.lang.Thread#sleep(long, int)
1467     */
1468    @TestTargetNew(
1469        level = TestLevel.COMPLETE,
1470        notes = "",
1471        method = "sleep",
1472        args = {long.class, int.class}
1473    )
1474    public void test_sleepJI() {
1475        // Test for method void java.lang.Thread.sleep(long, int)
1476
1477        // TODO : Test needs revisiting.
1478        long stime = 0, ftime = 0;
1479        try {
1480            stime = System.currentTimeMillis();
1481            Thread.sleep(1000, 999999);
1482            ftime = System.currentTimeMillis();
1483        } catch (InterruptedException e) {
1484            fail("Unexpected interrupt received");
1485        }
1486        long result = ftime - stime;
1487        assertTrue("Failed to sleep long enough: " + result, result >= 900
1488                && result <= 1100);
1489
1490        counter = 0;
1491        st = new Thread() {
1492
1493            public void run() {
1494                while(true) {
1495                    try {
1496                        sleep(0, 999999);
1497                        counter++;
1498                    } catch(InterruptedException e) {
1499
1500                    }
1501                }
1502            }
1503        };
1504
1505        st.start();
1506
1507        try {
1508            Thread.sleep(2, 999999);
1509        } catch(InterruptedException e) {
1510            fail("InterruptedException was thrown.");
1511        }
1512        assertEquals(2, counter);
1513
1514        st = new Thread() {
1515            public void run() {
1516                try {
1517                    sleep(10000, 999999);
1518                    fail("InterruptedException is thrown.");
1519                } catch(InterruptedException ie) {
1520                    //exception
1521                }
1522            }
1523        };
1524        st.start();
1525        st.interrupt();
1526    }
1527
1528    /**
1529     * @tests java.lang.Thread#start()
1530     */
1531    @TestTargetNew(
1532        level = TestLevel.COMPLETE,
1533        notes = "",
1534        method = "start",
1535        args = {}
1536    )
1537    public void test_start() {
1538        // Test for method void java.lang.Thread.start()
1539        try {
1540            ResSupThread t = new ResSupThread(Thread.currentThread());
1541            synchronized (t) {
1542                ct = new Thread(t, "Interrupt Test4");
1543                ct.start();
1544                t.wait();
1545            }
1546            assertTrue("Thread is not running1", ct.isAlive());
1547            // Let the child thread get going.
1548            int orgval = t.getCheckVal();
1549            Thread.sleep(150);
1550            assertTrue("Thread is not running2", orgval != t.getCheckVal());
1551            ct.interrupt();
1552        } catch (InterruptedException e) {
1553            fail("Unexpected interrupt occurred");
1554        }
1555        Thread thr = new Thread();
1556        thr.start();
1557        try {
1558            thr.start();
1559        } catch(IllegalThreadStateException itse){
1560            //expected
1561        }
1562    }
1563
1564    /**
1565     * @tests java.lang.Thread#stop()
1566     */
1567    @TestTargetNew(
1568        level = TestLevel.COMPLETE,
1569        notes = "",
1570        method = "stop",
1571        args = {}
1572    )
1573    @AndroidOnly("Android throws UnsupportedOperationException for Thread.stop()")
1574    @SuppressWarnings("deprecation")
1575    public void test_stop() {
1576        // Test for method void java.lang.Thread.stop()
1577        try {
1578            Runnable r = new ResSupThread(null);
1579            synchronized (r) {
1580                st = new Thread(r, "Interupt Test5");
1581                st.start();
1582                r.wait();
1583            }
1584
1585        } catch (InterruptedException e) {
1586            fail("Unexpected interrupt received");
1587        }
1588        try {
1589            st.stop();
1590            fail("Expected UnsupportedOperationException because" +
1591                    "Thread.stop is not supported.");
1592        } catch (UnsupportedOperationException e) {
1593            // expected
1594        }
1595
1596        // Security checks are made even though stop() is not supported.
1597        SecurityManager sm = new SecurityManager() {
1598            public void checkPermission(Permission perm) {
1599                if(perm.getName().equals("stopThread")) {
1600                    throw new SecurityException();
1601                }
1602            }
1603        };
1604        st = new Thread();
1605        SecurityManager oldSm = System.getSecurityManager();
1606        System.setSecurityManager(sm);
1607        try {
1608            st.stop();
1609            fail("Should throw SecurityException");
1610        } catch (SecurityException e) {
1611            // expected
1612        } finally {
1613            System.setSecurityManager(oldSm);
1614        }
1615    }
1616
1617    /**
1618     * @tests java.lang.Thread#stop(java.lang.Throwable)
1619     */
1620    @TestTargetNew(
1621        level = TestLevel.PARTIAL_COMPLETE,
1622        notes = "Verifies security.",
1623        method = "stop",
1624        args = {java.lang.Throwable.class}
1625    )
1626    @SuppressWarnings("deprecation")
1627    public void test_stopLjava_lang_Throwable_subtest0() {
1628        // Security checks are made even though stop(Throwable) is not supported.
1629        Thread t = new Thread("t");
1630        class MySecurityManager extends SecurityManager {
1631            @Override
1632            public void checkAccess(Thread t) {
1633               throw new SecurityException();
1634            }
1635            @Override
1636            public void checkPermission(Permission permission) {
1637
1638                if(permission.getName().equals("stopThread")) {
1639                    throw new SecurityException();
1640                }
1641            }
1642        }
1643        MySecurityManager sm = new MySecurityManager();
1644        System.setSecurityManager(sm);
1645        try {
1646            try {
1647                t.stop(new ThreadDeath());
1648                fail("SecurityException was thrown.");
1649            } catch (SecurityException e) {
1650            }
1651            t.start();
1652            try {
1653                t.join(1000);
1654            } catch (InterruptedException e) {
1655            }
1656            try {
1657                t.stop(new ThreadDeath());
1658                fail("SecurityException was thrown.");
1659            } catch (SecurityException e) {
1660            }
1661
1662        } finally {
1663            System.setSecurityManager(null);
1664        }
1665    }
1666
1667    /**
1668     * @tests java.lang.Thread#stop(java.lang.Throwable)
1669     */
1670    @TestTargetNew(
1671        level = TestLevel.PARTIAL_COMPLETE,
1672        notes = "SecurityException is not verified.",
1673        method = "stop",
1674        args = {java.lang.Throwable.class}
1675    )
1676    @AndroidOnly("Android throws UnsupportedOperationException for Thread.stop(Thorwable)")
1677    @SuppressWarnings("deprecation")
1678    public void test_stopLjava_lang_Throwable() {
1679        // Test for method void java.lang.Thread.stop(java.lang.Throwable)
1680        ResSupThread t = new ResSupThread(Thread.currentThread());
1681        synchronized (t) {
1682            st = new Thread(t, "StopThread");
1683            st.setPriority(Thread.MAX_PRIORITY);
1684            st.start();
1685            try {
1686                t.wait();
1687            } catch (InterruptedException e) {
1688            }
1689        }
1690        try {
1691            st.stop(new BogusException("Bogus"));
1692            fail("Expected UnsupportedOperationException because" +
1693                    "Thread.stop is not supported.");
1694        } catch (UnsupportedOperationException e) {
1695            // expected
1696        }
1697
1698        try {
1699            st.stop(null);
1700            fail("Expected NullPointerException was not thrown");
1701        } catch (NullPointerException e) {
1702            // expected
1703        }
1704    }
1705
1706    /**
1707     * @tests java.lang.Thread#suspend()
1708     */
1709    @TestTargetNew(
1710        level = TestLevel.COMPLETE,
1711        notes = "",
1712        method = "suspend",
1713        args = {}
1714    )
1715    @AndroidOnly("Android throws UnsupportedOperationException for Thread.suspend()")
1716    @SuppressWarnings("deprecation")
1717    public void test_suspend() {
1718        // Test for method void java.lang.Thread.suspend()
1719        int orgval;
1720        ResSupThread t = new ResSupThread(Thread.currentThread());
1721        try {
1722            synchronized (t) {
1723                ct = new Thread(t, "Interupt Test6");
1724                ct.start();
1725                t.wait();
1726            }
1727            ct.suspend();
1728            fail("Expected UnsupportedOperationException because" +
1729                    "Thread.suspend is not supported.");
1730        } catch (UnsupportedOperationException e) {
1731            // expected
1732        } catch (InterruptedException e) {
1733            fail("Unexpected InterruptedException was thrown");
1734        }
1735
1736        // Security checks are made even though suspend() is not supported.
1737        SecurityManager sm = new SecurityManager() {
1738            public void checkPermission(Permission perm) {
1739            }
1740
1741            public void checkAccess(Thread t) {
1742                throw new SecurityException();
1743            }
1744        };
1745        st = new Thread();
1746        SecurityManager oldSm = System.getSecurityManager();
1747        System.setSecurityManager(sm);
1748        try {
1749            st.suspend();
1750            fail("Should throw SecurityException");
1751        } catch (SecurityException e) {
1752            // expected
1753        } finally {
1754            System.setSecurityManager(oldSm);
1755        }
1756    }
1757
1758    /**
1759     * @tests java.lang.Thread#toString()
1760     */
1761    @TestTargetNew(
1762        level = TestLevel.COMPLETE,
1763        notes = "",
1764        method = "toString",
1765        args = {}
1766    )
1767    public void test_toString() {
1768        // Test for method java.lang.String java.lang.Thread.toString()
1769        ThreadGroup tg = new ThreadGroup("Test Group5");
1770        st = new Thread(tg, new SimpleThread(1), "SimpleThread17");
1771        final String stString = st.toString();
1772        final String expected = "Thread[SimpleThread17,5,Test Group5]";
1773        assertTrue("Returned incorrect string: " + stString + "\t(expecting :"
1774                + expected + ")", stString.equals(expected));
1775        st.start();
1776        try {
1777            st.join();
1778        } catch (InterruptedException e) {
1779        }
1780        tg.destroy();
1781    }
1782
1783    @TestTargetNew(
1784        level = TestLevel.COMPLETE,
1785        notes = "",
1786        method = "yield",
1787        args = {}
1788    )
1789    public void test_yield() {
1790
1791        Counter [] countersNotYeld = new Counter[10];
1792
1793        for(int i = 0; i < 10; i++) {
1794            countersNotYeld[i] = new Counter(false);
1795        }
1796        Counter countersYeld = new Counter(true);
1797        try {
1798            Thread.sleep(11000);
1799        } catch(InterruptedException ie) {}
1800
1801        for(Counter c:countersNotYeld) {
1802            assertTrue(countersYeld.counter == c.counter);
1803        }
1804    }
1805
1806    class Counter extends Thread {
1807        public int counter = 0;
1808        boolean isDoYield = false;
1809
1810        public Counter(boolean isDoYield) {
1811            this.isDoYield = isDoYield;
1812            start();
1813        }
1814
1815        public void run() {
1816            for(int i = 0; i < 10000; i++) {
1817                if(isDoYield)
1818                    yield();
1819                counter ++;
1820            }
1821        }
1822    }
1823
1824
1825    /**
1826     * @tests java.lang.Thread#getAllStackTraces()
1827     */
1828    @TestTargetNew(
1829        level = TestLevel.COMPLETE,
1830        notes = "",
1831        method = "getAllStackTraces",
1832        args = {}
1833    )
1834    public void test_getAllStackTraces() {
1835        Map<Thread, StackTraceElement[]> stMap = Thread.getAllStackTraces();
1836        assertNotNull(stMap);
1837        //TODO add security-based tests
1838
1839        SecurityManager sm = new SecurityManager() {
1840
1841            public void checkPermission(Permission perm) {
1842                if(perm.getName().equals("modifyThreadGroup")) {
1843                    throw new SecurityException();
1844                }
1845            }
1846        };
1847
1848        SecurityManager oldSm = System.getSecurityManager();
1849        System.setSecurityManager(sm);
1850        try {
1851            Thread.getAllStackTraces();
1852            fail("Should throw SecurityException");
1853        } catch (SecurityException e) {
1854            // expected
1855        } finally {
1856           System.setSecurityManager(oldSm);
1857        }
1858    }
1859
1860    /**
1861     * @tests java.lang.Thread#getDefaultUncaughtExceptionHandler
1862     * @tests java.lang.Thread#setDefaultUncaughtExceptionHandler
1863     */
1864    @TestTargets({
1865        @TestTargetNew(
1866            level = TestLevel.COMPLETE,
1867            notes = "",
1868            method = "setDefaultUncaughtExceptionHandler",
1869            args = {java.lang.Thread.UncaughtExceptionHandler.class}
1870        ),
1871        @TestTargetNew(
1872            level = TestLevel.COMPLETE,
1873            notes = "",
1874            method = "getDefaultUncaughtExceptionHandler",
1875            args = {}
1876        )
1877    })
1878    public void test_get_setDefaultUncaughtExceptionHandler() {
1879        class Handler implements UncaughtExceptionHandler {
1880            public void uncaughtException(Thread thread, Throwable ex) {
1881            }
1882        }
1883
1884        final Handler handler = new Handler();
1885        Thread.setDefaultUncaughtExceptionHandler(handler);
1886        assertSame(handler, Thread.getDefaultUncaughtExceptionHandler());
1887
1888        Thread.setDefaultUncaughtExceptionHandler(null);
1889        assertNull(Thread.getDefaultUncaughtExceptionHandler());
1890        //TODO add security-based tests
1891
1892        SecurityManager sm = new SecurityManager() {
1893
1894            public void checkPermission(Permission perm) {
1895                if(perm.getName().
1896                        equals("setDefaultUncaughtExceptionHandler")) {
1897                    throw new SecurityException();
1898                }
1899            }
1900        };
1901
1902        SecurityManager oldSm = System.getSecurityManager();
1903        System.setSecurityManager(sm);
1904        try {
1905            st.setDefaultUncaughtExceptionHandler(handler);
1906            fail("Should throw SecurityException");
1907        } catch (SecurityException e) {
1908            // expected
1909        }  finally {
1910            System.setSecurityManager(oldSm);
1911        }
1912    }
1913
1914    /**
1915     * @tests java.lang.Thread#getStackTrace()
1916     */
1917    @TestTargetNew(
1918        level = TestLevel.COMPLETE,
1919        notes = "",
1920        method = "getStackTrace",
1921        args = {}
1922    )
1923    public void test_getStackTrace() {
1924        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
1925
1926        assertNotNull(stackTrace);
1927
1928        stack_trace_loop: {
1929            for (int i = 0; i < stackTrace.length; i++) {
1930                StackTraceElement e = stackTrace[i];
1931                if (getClass().getName().equals(e.getClassName())) {
1932                    if ("test_getStackTrace".equals(e.getMethodName())) {
1933                        break stack_trace_loop;
1934                    }
1935                }
1936            }
1937            fail("class and method not found in stack trace");
1938        }
1939
1940        //TODO add security-based tests
1941
1942        SecurityManager sm = new SecurityManager() {
1943
1944            public void checkPermission(Permission perm) {
1945                if(perm.getName().
1946                        equals("getStackTrace")) {
1947                    throw new SecurityException();
1948                }
1949            }
1950        };
1951        st = new Thread();
1952        SecurityManager oldSm = System.getSecurityManager();
1953        System.setSecurityManager(sm);
1954        try {
1955            st.getStackTrace();
1956            fail("Should throw SecurityException");
1957        } catch (SecurityException e) {
1958            // expected
1959        }  finally {
1960            System.setSecurityManager(oldSm);
1961        }
1962    }
1963
1964    /**
1965     * @tests java.lang.Thread#getState()
1966     */
1967    @TestTargetNew(
1968        level = TestLevel.COMPLETE,
1969        notes = "",
1970        method = "getState",
1971        args = {}
1972    )
1973    public void test_getState() {
1974        Thread.State state = Thread.currentThread().getState();
1975        assertNotNull(state);
1976        assertEquals(Thread.State.RUNNABLE, state);
1977
1978        final Semaphore sem = new Semaphore(0);
1979        final Object lock = new Object();
1980        Thread th = new Thread() {
1981            @Override
1982            public void run() {
1983                  while (!sem.hasQueuedThreads()) {}
1984                  sem.release();
1985                  while (run) {}
1986                  try {
1987                      sem.acquire();
1988                  } catch (InterruptedException e) {
1989                      fail("InterruptedException was thrown.");
1990                  }
1991                  synchronized (lock) {
1992                      lock.equals(new Object());
1993                  }
1994                  synchronized (lock) {
1995                      try {
1996                        sem.release();
1997                        lock.wait(Long.MAX_VALUE);
1998                      } catch (InterruptedException e) {
1999                          // expected
2000                      }
2001                  }
2002            }
2003        };
2004        assertEquals(Thread.State.NEW, th.getState());
2005        th.start();
2006        try {
2007            sem.acquire();
2008        } catch (InterruptedException e) {
2009            fail("InterruptedException was thrown.");
2010        }
2011        assertEquals(Thread.State.RUNNABLE, th.getState());
2012        run = false;
2013
2014        while (!sem.hasQueuedThreads()){}
2015
2016        assertEquals(Thread.State.WAITING, th.getState());
2017        synchronized (lock) {
2018            sem.release();
2019            long start = System.currentTimeMillis();
2020            while(start + 1000 > System.currentTimeMillis()) {}
2021            assertEquals(Thread.State.BLOCKED, th.getState());
2022        }
2023
2024        try {
2025            sem.acquire();
2026        } catch (InterruptedException e) {
2027            fail("InterruptedException was thrown.");
2028        }
2029
2030        synchronized (lock) {
2031            assertEquals(Thread.State.TIMED_WAITING, th.getState());
2032            th.interrupt();
2033        }
2034
2035        try {
2036            th.join(1000);
2037        } catch(InterruptedException ie) {
2038            fail("InterruptedException was thrown.");
2039        }
2040        assertEquals(Thread.State.TERMINATED, th.getState());
2041    }
2042    boolean run = true;
2043
2044    /**
2045     * @tests java.lang.Thread#getUncaughtExceptionHandler
2046     * @tests java.lang.Thread#setUncaughtExceptionHandler
2047     */
2048    @TestTargets({
2049        @TestTargetNew(
2050            level = TestLevel.COMPLETE,
2051            notes = "",
2052            method = "getUncaughtExceptionHandler",
2053            args = {}
2054        ),
2055        @TestTargetNew(
2056            level = TestLevel.COMPLETE,
2057            notes = "",
2058            method = "setUncaughtExceptionHandler",
2059            args = {java.lang.Thread.UncaughtExceptionHandler.class}
2060        )
2061    })
2062    public void test_get_setUncaughtExceptionHandler() {
2063        class Handler implements UncaughtExceptionHandler {
2064            public void uncaughtException(Thread thread, Throwable ex) {
2065            }
2066        }
2067
2068        final Handler handler = new Handler();
2069        Thread.currentThread().setUncaughtExceptionHandler(handler);
2070        assertSame(handler, Thread.currentThread().getUncaughtExceptionHandler());
2071
2072        Thread.currentThread().setUncaughtExceptionHandler(null);
2073
2074        //TODO add security-based tests
2075        SecurityManager sm = new SecurityManager() {
2076
2077            public void checkPermission(Permission perm) {
2078            }
2079
2080            public void checkAccess(Thread t) {
2081               throw new SecurityException();
2082            }
2083        };
2084        st = new Thread();
2085        SecurityManager oldSm = System.getSecurityManager();
2086        System.setSecurityManager(sm);
2087        try {
2088            st.setUncaughtExceptionHandler(handler);
2089            fail("Should throw SecurityException");
2090        } catch (SecurityException e) {
2091            // expected
2092        } finally {
2093            System.setSecurityManager(oldSm);
2094        }
2095
2096    }
2097
2098    /**
2099     * @tests java.lang.Thread#getId()
2100     */
2101    @TestTargetNew(
2102        level = TestLevel.COMPLETE,
2103        notes = "",
2104        method = "getId",
2105        args = {}
2106    )
2107    public void test_getId() {
2108        assertTrue("current thread's ID is not positive", Thread.currentThread().getId() > 0);
2109
2110        //check all the current threads for positive IDs
2111        Map<Thread, StackTraceElement[]> stMap = Thread.getAllStackTraces();
2112        for (Thread thread : stMap.keySet()) {
2113            assertTrue("thread's ID is not positive: " + thread.getName(), thread.getId() > 0);
2114        }
2115    }
2116
2117    /**
2118     * @tests java.lang.Thread#holdLock()
2119     */
2120    @TestTargetNew(
2121        level = TestLevel.COMPLETE,
2122        notes = "",
2123        method = "holdsLock",
2124        args = {java.lang.Object.class}
2125    )
2126    public void test_holdsLock() {
2127        MonitoredClass monitor = new MonitoredClass();
2128
2129        monitor.enterLocked();
2130        monitor.enterNonLocked();
2131
2132        try {
2133            Thread.holdsLock(null);
2134            fail("NullPointerException was not thrown.");
2135        } catch(NullPointerException npe) {
2136            //expected
2137        }
2138    }
2139
2140    @Override
2141    protected void tearDown() {
2142        try {
2143            if (st != null)
2144                st.interrupt();
2145        } catch (Exception e) {
2146        }
2147        try {
2148            if (spinner != null)
2149                spinner.interrupt();
2150        } catch (Exception e) {
2151        }
2152        try {
2153            if (ct != null)
2154                ct.interrupt();
2155        } catch (Exception e) {
2156        }
2157
2158        try {
2159            spinner = null;
2160            st = null;
2161            ct = null;
2162            System.runFinalization();
2163        } catch (Exception e) {
2164        }
2165    }
2166}
2167