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