ThreadTest.java revision d8c2a9cec82df89dd2275e1c8c260b8eaf831e56
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 orgCount = Thread.enumerate(tarray);
542                    synchronized (st1) {
543                        firstOne.start();
544                        try {
545                            st1.wait();
546                        } catch (InterruptedException e) {
547                        }
548                    }
549                    int count = Thread.enumerate(tarray);
550                    assertEquals("Incorrect value returned2",
551                            orgCount + 1, count);
552                    synchronized (st2) {
553                        secondOne.start();
554                        try {
555                            st2.wait();
556                        } catch (InterruptedException e) {
557                        }
558                    }
559                    count = Thread.enumerate(tarray);
560                    assertEquals("Incorrect value returned3",
561                            orgCount + 2, count);
562                } catch (junit.framework.AssertionFailedError e) {
563                    failed = true;
564                    failMessage = e.getMessage();
565                    e.printStackTrace();
566                } finally {
567                    synchronized (st1) {
568                        firstOne.interrupt();
569                    }
570                    synchronized (st2) {
571                        secondOne.interrupt();
572                    }
573                    try {
574                        firstOne.join();
575                        secondOne.join();
576                    } catch (InterruptedException e) {
577                    }
578                    mytg.destroy();
579                }
580            }
581        };
582
583        ThreadGroup tg = new ThreadGroup("tg");
584        MyThread t = new MyThread(tg, "top");
585        t.start();
586        try {
587            t.join();
588        } catch (InterruptedException e) {
589            fail("Unexpected interrupt");
590        } finally {
591            tg.destroy();
592        }
593        assertFalse(t.failMessage, t.failed);
594    }
595
596    /**
597     * @tests java.lang.Thread#getContextClassLoader()
598     */
599    @TestTargetNew(
600        level = TestLevel.COMPLETE,
601        notes = "",
602        method = "getContextClassLoader",
603        args = {}
604    )
605    public void test_getContextClassLoader() {
606        // Test for method java.lang.ClassLoader
607        // java.lang.Thread.getContextClassLoader()
608        Thread t = new Thread();
609        assertTrue("Incorrect class loader returned",
610                t.getContextClassLoader() == Thread.currentThread()
611                        .getContextClassLoader());
612        t.start();
613
614 /*       SecurityManager sm = new SecurityManager() {
615
616            public void checkPermission(Permission perm) {
617                if(perm.getName().equals("getClassLoader")) {
618                    throw new SecurityException();
619                }
620            }
621        };
622
623        SecurityManager oldSm = System.getSecurityManager();
624        System.setSecurityManager(sm);
625        try {
626            t.getContextClassLoader();
627            fail("Should throw SecurityException");
628        } catch (SecurityException e) {
629            // expected
630        } finally {
631           System.setSecurityManager(oldSm);
632        }
633*/
634    }
635
636    /**
637     * @tests java.lang.Thread#getName()
638     */
639    @TestTargetNew(
640        level = TestLevel.COMPLETE,
641        notes = "",
642        method = "getName",
643        args = {}
644    )
645    public void test_getName() {
646        // Test for method java.lang.String java.lang.Thread.getName()
647        st = new Thread(new SimpleThread(1), "SimpleThread6");
648        assertEquals("Returned incorrect thread name",
649                "SimpleThread6", st.getName());
650        st.start();
651    }
652
653    /**
654     * @tests java.lang.Thread#getPriority()
655     */
656    @TestTargetNew(
657        level = TestLevel.COMPLETE,
658        notes = "",
659        method = "getPriority",
660        args = {}
661    )
662    public void test_getPriority() {
663        // Test for method int java.lang.Thread.getPriority()
664        st = new Thread(new SimpleThread(1));
665        st.setPriority(Thread.MAX_PRIORITY);
666        assertTrue("Returned incorrect thread priority",
667                st.getPriority() == Thread.MAX_PRIORITY);
668        st.start();
669    }
670
671    /**
672     * @tests java.lang.Thread#getThreadGroup()
673     */
674    @TestTargetNew(
675        level = TestLevel.COMPLETE,
676        notes = "",
677        method = "getThreadGroup",
678        args = {}
679    )
680    public void test_getThreadGroup() {
681        // Test for method java.lang.ThreadGroup
682        // java.lang.Thread.getThreadGroup()
683        ThreadGroup tg = new ThreadGroup("Test Group4");
684        st = new Thread(tg, /* new SimpleThread(1), */ "SimpleThread8");
685        assertTrue("Returned incorrect thread group", st.getThreadGroup() == tg);
686        st.start();
687        try {
688            st.join();
689        } catch (InterruptedException e) {
690        }
691        assertNull("group should be null", st.getThreadGroup());
692        assertNotNull("toString() should not be null", st.toString());
693        tg.destroy();
694
695        final Object lock = new Object();
696        Thread t = new Thread() {
697            @Override
698            public void run() {
699                synchronized (lock) {
700                    lock.notifyAll();
701                }
702            }
703        };
704        synchronized (lock) {
705            t.start();
706            try {
707                lock.wait();
708            } catch (InterruptedException e) {
709            }
710        }
711        int running = 0;
712        while (t.isAlive())
713            running++;
714        ThreadGroup group = t.getThreadGroup();
715        assertNull("ThreadGroup is not null", group);
716    }
717
718    /**
719     * @tests java.lang.Thread#interrupt()
720     */
721    @TestTargetNew(
722        level = TestLevel.COMPLETE,
723        notes = "",
724        method = "interrupt",
725        args = {}
726    )
727    public void test_interrupt() {
728        // Test for method void java.lang.Thread.interrupt()
729        final Object lock = new Object();
730        class ChildThread1 extends Thread {
731            Thread parent;
732
733            boolean sync;
734
735            @Override
736            public void run() {
737                if (sync) {
738                    synchronized (lock) {
739                        lock.notify();
740                        try {
741                            lock.wait();
742                        } catch (InterruptedException e) {
743                        }
744                    }
745                }
746                parent.interrupt();
747            }
748
749            public ChildThread1(Thread p, String name, boolean sync) {
750                super(name);
751                parent = p;
752                this.sync = sync;
753            }
754        }
755        boolean interrupted = false;
756        try {
757            ct = new ChildThread1(Thread.currentThread(), "Interrupt Test1",
758                    false);
759            synchronized (lock) {
760                ct.start();
761                lock.wait();
762            }
763        } catch (InterruptedException e) {
764            interrupted = true;
765        }
766        assertTrue("Failed to Interrupt thread1", interrupted);
767
768        interrupted = false;
769        try {
770            ct = new ChildThread1(Thread.currentThread(), "Interrupt Test2",
771                    true);
772            synchronized (lock) {
773                ct.start();
774                lock.wait();
775                lock.notify();
776            }
777            Thread.sleep(20000);
778        } catch (InterruptedException e) {
779            interrupted = true;
780        }
781        assertTrue("Failed to Interrupt thread2", interrupted);
782
783        SecurityManager sm = new SecurityManager() {
784
785            public void checkPermission(Permission perm) {
786            }
787
788            public void checkAccess(Thread t) {
789               throw new SecurityException();
790            }
791        };
792        st = new Thread();
793        SecurityManager oldSm = System.getSecurityManager();
794        System.setSecurityManager(sm);
795        try {
796            st.interrupt();
797            fail("Should throw SecurityException");
798        } catch (SecurityException e) {
799            // expected
800        } finally {
801           System.setSecurityManager(oldSm);
802        }
803    }
804
805    /**
806     * @tests java.lang.Thread#interrupted()
807     */
808    @TestTargetNew(
809        level = TestLevel.COMPLETE,
810        notes = "",
811        method = "interrupted",
812        args = {}
813    )
814    public void test_interrupted() {
815        assertFalse("Interrupted returned true for non-interrupted thread", Thread
816                .interrupted());
817        Thread.currentThread().interrupt();
818        assertTrue("Interrupted returned true for non-interrupted thread", Thread.interrupted());
819        assertFalse("Failed to clear interrupted flag", Thread.interrupted());
820    }
821
822    /**
823     * @tests java.lang.Thread#isAlive()
824     */
825    @TestTargetNew(
826        level = TestLevel.COMPLETE,
827        notes = "",
828        method = "isAlive",
829        args = {}
830    )
831    public void test_isAlive() {
832        // Test for method boolean java.lang.Thread.isAlive()
833        SimpleThread simple;
834        st = new Thread(simple = new SimpleThread(500));
835        assertFalse("A thread that wasn't started is alive.", st.isAlive());
836        synchronized (simple) {
837            st.start();
838            try {
839                simple.wait();
840            } catch (InterruptedException e) {
841            }
842        }
843        assertTrue("Started thread returned false", st.isAlive());
844
845        try {
846            st.join();
847        } catch (InterruptedException e) {
848            fail("Thread did not die");
849        }
850        assertTrue("Stopped thread returned true", !st.isAlive());
851    }
852
853    /**
854     * @tests java.lang.Thread#isDaemon()
855     */
856    @TestTargetNew(
857        level = TestLevel.COMPLETE,
858        notes = "",
859        method = "isDaemon",
860        args = {}
861    )
862    public void test_isDaemon() {
863        // Test for method boolean java.lang.Thread.isDaemon()
864        st = new Thread(new SimpleThread(1), "SimpleThread10");
865        assertTrue("Non-Daemon thread returned true", !st.isDaemon());
866        st.setDaemon(true);
867        assertTrue("Daemon thread returned false", st.isDaemon());
868        st.start();
869    }
870
871    /**
872     * @tests java.lang.Thread#isInterrupted()
873     */
874    @TestTargetNew(
875        level = TestLevel.COMPLETE,
876        notes = "",
877        method = "isInterrupted",
878        args = {}
879    )
880    public void test_isInterrupted() {
881        // Test for method boolean java.lang.Thread.isInterrupted()
882        class SpinThread implements Runnable {
883            public volatile boolean done = false;
884
885            public void run() {
886                while (!Thread.currentThread().isInterrupted())
887                    ;
888                while (!done)
889                    ;
890            }
891        }
892
893        SpinThread spin = new SpinThread();
894        spinner = new Thread(spin);
895        spinner.start();
896        Thread.yield();
897        try {
898            assertTrue("Non-Interrupted thread returned true", !spinner
899                    .isInterrupted());
900            spinner.interrupt();
901            assertTrue("Interrupted thread returned false", spinner
902                    .isInterrupted());
903            spin.done = true;
904        } finally {
905            spinner.interrupt();
906            spin.done = true;
907        }
908    }
909
910    /**
911     * @tests java.lang.Thread#join()
912     */
913    @TestTargetNew(
914        level = TestLevel.COMPLETE,
915        notes = "",
916        method = "join",
917        args = {}
918    )
919    public void test_join() {
920        // Test for method void java.lang.Thread.join()
921        SimpleThread simple;
922        try {
923            st = new Thread(simple = new SimpleThread(100));
924            // cause isAlive() to be compiled by the JIT, as it must be called
925            // within 100ms below.
926            assertTrue("Thread is alive", !st.isAlive());
927            synchronized (simple) {
928                st.start();
929                simple.wait();
930            }
931            st.join();
932        } catch (InterruptedException e) {
933            fail("Join failed ");
934        }
935        assertTrue("Joined thread is still alive", !st.isAlive());
936        boolean result = true;
937        Thread th = new Thread("test");
938        try {
939            th.join();
940        } catch (InterruptedException e) {
941            result = false;
942        }
943        assertTrue("Hung joining a non-started thread", result);
944        th.start();
945
946        st = new Thread() {
947            public void run() {
948                try {
949                    join();
950                    fail("InterruptedException was not thrown.");
951                } catch(InterruptedException ie) {
952                    //expected
953                }
954            }
955        };
956
957        st.start();
958    }
959
960    /**
961     * @tests java.lang.Thread#join(long)
962     */
963    @TestTargetNew(
964        level = TestLevel.COMPLETE,
965        notes = "",
966        method = "join",
967        args = {long.class}
968    )
969    public void test_joinJ() {
970        // Test for method void java.lang.Thread.join(long)
971        SimpleThread simple;
972        try {
973            st = new Thread(simple = new SimpleThread(1000), "SimpleThread12");
974            // cause isAlive() to be compiled by the JIT, as it must be called
975            // within 100ms below.
976            assertTrue("Thread is alive", !st.isAlive());
977            synchronized (simple) {
978                st.start();
979                simple.wait();
980            }
981            st.join(10);
982        } catch (InterruptedException e) {
983            fail("Join failed ");
984        }
985        assertTrue("Join failed to timeout", st.isAlive());
986
987        st.interrupt();
988        try {
989            st = new Thread(simple = new SimpleThread(100), "SimpleThread13");
990            synchronized (simple) {
991                st.start();
992                simple.wait();
993            }
994            st.join(1000);
995        } catch (InterruptedException e) {
996            fail("Join failed : " + e.getMessage());
997            return;
998        }
999        assertTrue("Joined thread is still alive", !st.isAlive());
1000
1001        final Object lock = new Object();
1002        final Thread main = Thread.currentThread();
1003        Thread killer = new Thread(new Runnable() {
1004            public void run() {
1005                try {
1006                    synchronized (lock) {
1007                        lock.notify();
1008                    }
1009                    Thread.sleep(100);
1010                } catch (InterruptedException e) {
1011                    return;
1012                }
1013                main.interrupt();
1014            }
1015        });
1016        boolean result = true;
1017        Thread th = new Thread("test");
1018        try {
1019            synchronized (lock) {
1020                killer.start();
1021                lock.wait();
1022            }
1023            th.join(200);
1024        } catch (InterruptedException e) {
1025            result = false;
1026        }
1027        killer.interrupt();
1028        assertTrue("Hung joining a non-started thread", result);
1029        th.start();
1030
1031        st = new Thread() {
1032            public void run() {
1033                try {
1034                    join(1000);
1035                    fail("InterruptedException was not thrown.");
1036                } catch(InterruptedException ie) {
1037                    //expected
1038                }
1039            }
1040        };
1041
1042        st.start();
1043    }
1044
1045    /**
1046     * @tests java.lang.Thread#join(long, int)
1047     */
1048    @TestTargetNew(
1049        level = TestLevel.COMPLETE,
1050        notes = "",
1051        method = "join",
1052        args = {long.class, int.class}
1053    )
1054    public void test_joinJI() {
1055        // Test for method void java.lang.Thread.join(long, int)
1056        SimpleThread simple;
1057        try {
1058            st = new Thread(simple = new SimpleThread(1000), "Squawk1");
1059            assertTrue("Thread is alive", !st.isAlive());
1060            synchronized (simple) {
1061                st.start();
1062                simple.wait();
1063            }
1064
1065            long firstRead = System.currentTimeMillis();
1066            st.join(100, 999999);
1067            long secondRead = System.currentTimeMillis();
1068            assertTrue("Did not join by appropriate time: " + secondRead + "-"
1069                    + firstRead + "=" + (secondRead - firstRead), secondRead
1070                    - firstRead <= 300);
1071            assertTrue("Joined thread is not alive", st.isAlive());
1072            st.interrupt();
1073        } catch (Exception e) {
1074            fail("Exception during test : " + e.getMessage());
1075        }
1076
1077        final Object lock = new Object();
1078        final Thread main = Thread.currentThread();
1079        Thread killer = new Thread(new Runnable() {
1080            public void run() {
1081                try {
1082                    synchronized (lock) {
1083                        lock.notify();
1084                    }
1085                    Thread.sleep(100);
1086                } catch (InterruptedException e) {
1087                    return;
1088                }
1089                main.interrupt();
1090            }
1091        });
1092        boolean result = true;
1093        Thread th = new Thread("test");
1094        try {
1095            synchronized (lock) {
1096                killer.start();
1097                lock.wait();
1098            }
1099            th.join(200, 20);
1100        } catch (InterruptedException e) {
1101            result = false;
1102        }
1103        killer.interrupt();
1104        assertTrue("Hung joining a non-started thread", result);
1105        th.start();
1106
1107        st = new Thread() {
1108            public void run() {
1109                try {
1110                    join(1000, 20);
1111                    fail("InterruptedException was not thrown.");
1112                } catch(InterruptedException ie) {
1113                    //expected
1114                }
1115            }
1116        };
1117
1118        st.start();
1119    }
1120
1121    @TestTargets({
1122        @TestTargetNew(
1123            level = TestLevel.COMPLETE,
1124            notes = "",
1125            method = "setContextClassLoader",
1126            args = {java.lang.ClassLoader.class}
1127        ),
1128        @TestTargetNew(
1129            level = TestLevel.COMPLETE,
1130            notes = "",
1131            method = "getContextClassLoader",
1132            args = {}
1133        )
1134    })
1135    public void test_setContextClassLoader() {
1136        PublicClassLoader pcl = new PublicClassLoader();
1137        st = new Thread();
1138        st.setContextClassLoader(pcl);
1139        assertEquals(pcl, st.getContextClassLoader());
1140
1141        st.setContextClassLoader(null);
1142        assertNull(st.getContextClassLoader());
1143
1144        SecurityManager sm = new SecurityManager() {
1145            public void checkPermission(Permission perm) {
1146                if (perm.getName().equals("setContextClassLoader")
1147                        || perm.getName().equals("getClassLoader") ) {
1148                    throw new SecurityException();
1149                }
1150            }
1151        };
1152
1153        SecurityManager oldSm = System.getSecurityManager();
1154        System.setSecurityManager(sm);
1155        try {
1156            st.setContextClassLoader(pcl);
1157            fail("Should throw SecurityException");
1158        } catch (SecurityException e) {
1159            // expected
1160        } finally {
1161            System.setSecurityManager(oldSm);
1162        }
1163    }
1164
1165
1166    /**
1167     * @tests java.lang.Thread#resume()
1168     */
1169    @TestTargetNew(
1170        level = TestLevel.COMPLETE,
1171        notes = "",
1172        method = "resume",
1173        args = {}
1174    )
1175    @AndroidOnly("Android throws UnsupportedOperationException for Thread.resume()")
1176    @SuppressWarnings("deprecation")
1177    public void test_resume() {
1178        // Test for method void java.lang.Thread.resume()
1179        int orgval;
1180        ResSupThread t;
1181        try {
1182            t = new ResSupThread(Thread.currentThread());
1183            synchronized (t) {
1184                ct = new Thread(t, "Interrupt Test2");
1185                ct.start();
1186                t.wait();
1187            }
1188            try {
1189                ct.resume();
1190            } catch (UnsupportedOperationException e) {
1191                // expected
1192            }
1193        } catch (InterruptedException e) {
1194            fail("Unexpected interrupt occurred : " + e.getMessage());
1195        }
1196
1197        // Security checks are made even though resume() is not supported.
1198        SecurityManager sm = new SecurityManager() {
1199            public void checkPermission(Permission perm) {
1200            }
1201
1202            public void checkAccess(Thread t) {
1203                throw new SecurityException();
1204            }
1205        };
1206        st = new Thread();
1207        SecurityManager oldSm = System.getSecurityManager();
1208        System.setSecurityManager(sm);
1209        try {
1210            st.resume();
1211            fail("Should throw SecurityException");
1212        } catch (SecurityException e) {
1213            // expected
1214        } finally {
1215            System.setSecurityManager(oldSm);
1216        }
1217    }
1218
1219    /**
1220     * @tests java.lang.Thread#run()
1221     */
1222    @TestTargetNew(
1223        level = TestLevel.COMPLETE,
1224        notes = "",
1225        method = "run",
1226        args = {}
1227    )
1228    public void test_run() {
1229        // Test for method void java.lang.Thread.run()
1230        class RunThread implements Runnable {
1231            boolean didThreadRun = false;
1232
1233            public void run() {
1234                didThreadRun = true;
1235            }
1236        }
1237        RunThread rt = new RunThread();
1238        Thread t = new Thread(rt);
1239        try {
1240            t.start();
1241            int count = 0;
1242            while (!rt.didThreadRun && count < 20) {
1243                Thread.sleep(100);
1244                count++;
1245            }
1246            assertTrue("Thread did not run", rt.didThreadRun);
1247            t.join();
1248        } catch (InterruptedException e) {
1249            assertTrue("Joined thread was interrupted", true);
1250        }
1251        assertTrue("Joined thread is still alive", !t.isAlive());
1252    }
1253
1254    /**
1255     * @tests java.lang.Thread#setDaemon(boolean)
1256     */
1257    @TestTargetNew(
1258        level = TestLevel.COMPLETE,
1259        notes = "",
1260        method = "setDaemon",
1261        args = {boolean.class}
1262    )
1263    public void test_setDaemonZ() {
1264        // Test for method void java.lang.Thread.setDaemon(boolean)
1265        st = new Thread(new SimpleThread(1), "SimpleThread14");
1266        st.setDaemon(true);
1267        assertTrue("Failed to set thread as daemon thread", st.isDaemon());
1268        st.start();
1269
1270        // BEGIN android-added
1271        st = new Thread(new SimpleThread(5));
1272        st.start();
1273        try {
1274            st.setDaemon(false);
1275            fail("setDaemon() must throw exception for started thread");
1276        } catch (IllegalThreadStateException ex) {
1277            // We expect this one.
1278        }
1279        // END android-added
1280
1281        SecurityManager sm = new SecurityManager() {
1282
1283            public void checkPermission(Permission perm) {
1284            }
1285
1286            public void checkAccess(Thread t) {
1287               throw new SecurityException();
1288            }
1289        };
1290
1291        SecurityManager oldSm = System.getSecurityManager();
1292        System.setSecurityManager(sm);
1293        try {
1294            st.setDaemon(false);
1295            fail("Should throw SecurityException");
1296        } catch (SecurityException e) {
1297            // expected
1298        } finally {
1299            System.setSecurityManager(oldSm);
1300        }
1301    }
1302
1303    /**
1304     * @tests java.lang.Thread#setName(java.lang.String)
1305     */
1306    @TestTargetNew(
1307        level = TestLevel.COMPLETE,
1308        notes = "",
1309        method = "setName",
1310        args = {java.lang.String.class}
1311    )
1312    public void test_setNameLjava_lang_String() {
1313        // Test for method void java.lang.Thread.setName(java.lang.String)
1314        st = new Thread(new SimpleThread(1), "SimpleThread15");
1315        st.setName("Bogus Name");
1316        assertEquals("Failed to set thread name",
1317                "Bogus Name", st.getName());
1318        try {
1319            st.setName(null);
1320            fail("Null should not be accepted as a valid name");
1321        } catch (NullPointerException e) {
1322            // success
1323            assertTrue("Null should not be accepted as a valid name", true);
1324        }
1325        st.start();
1326
1327        SecurityManager sm = new SecurityManager() {
1328
1329            public void checkPermission(Permission perm) {
1330            }
1331
1332            public void checkAccess(Thread t) {
1333               throw new SecurityException();
1334            }
1335        };
1336
1337        SecurityManager oldSm = System.getSecurityManager();
1338        System.setSecurityManager(sm);
1339        try {
1340            st.setName("Bogus Name");
1341            fail("Should throw SecurityException");
1342        } catch (SecurityException e) {
1343            // expected
1344        } finally {
1345           System.setSecurityManager(oldSm);
1346        }
1347    }
1348
1349    /**
1350     * @tests java.lang.Thread#setPriority(int)
1351     */
1352    @TestTargetNew(
1353        level = TestLevel.COMPLETE,
1354        notes = "",
1355        method = "setPriority",
1356        args = {int.class}
1357    )
1358    public void test_setPriorityI() {
1359        // Test for method void java.lang.Thread.setPriority(int)
1360        st = new Thread(new SimpleThread(1));
1361        st.setPriority(Thread.MAX_PRIORITY);
1362        assertTrue("Failed to set priority",
1363                st.getPriority() == Thread.MAX_PRIORITY);
1364        st.start();
1365
1366        SecurityManager sm = new SecurityManager() {
1367
1368            public void checkPermission(Permission perm) {
1369            }
1370
1371            public void checkAccess(Thread t) {
1372               throw new SecurityException();
1373            }
1374        };
1375
1376        SecurityManager oldSm = System.getSecurityManager();
1377        System.setSecurityManager(sm);
1378        try {
1379            st.setPriority(Thread.MIN_PRIORITY);
1380            fail("Should throw SecurityException");
1381        } catch (SecurityException e) {
1382            // expected
1383        } finally {
1384            System.setSecurityManager(oldSm);
1385        }
1386
1387        try {
1388            st.setPriority(Thread.MIN_PRIORITY - 1);
1389            fail("IllegalArgumentException is not thrown.");
1390        } catch(IllegalArgumentException iae) {
1391            //expected
1392        }
1393
1394        try {
1395            st.setPriority(Thread.MAX_PRIORITY + 1);
1396            fail("IllegalArgumentException is not thrown.");
1397        } catch(IllegalArgumentException iae) {
1398            //expected
1399        }
1400    }
1401
1402    /**
1403     * @tests java.lang.Thread#sleep(long)
1404     */
1405    @TestTargetNew(
1406        level = TestLevel.COMPLETE,
1407        notes = "",
1408        method = "sleep",
1409        args = {long.class}
1410    )
1411    public void test_sleepJ() {
1412        // Test for method void java.lang.Thread.sleep(long)
1413
1414        // TODO : Test needs enhancing.
1415        long stime = 0, ftime = 0;
1416        try {
1417            stime = System.currentTimeMillis();
1418            Thread.sleep(1000);
1419            ftime = System.currentTimeMillis();
1420        } catch (InterruptedException e) {
1421            fail("Unexpected interrupt received");
1422        }
1423        assertTrue("Failed to sleep long enough", (ftime - stime) >= 800);
1424
1425        counter = 0;
1426        st = new Thread() {
1427
1428            public void run() {
1429                while(true) {
1430                    try {
1431                        sleep(1000);
1432                        counter++;
1433                    } catch(InterruptedException e) {
1434
1435                    }
1436                }
1437            }
1438        };
1439
1440        st.start();
1441
1442        try {
1443            Thread.sleep(5000);
1444        } catch(InterruptedException e) {
1445            fail("InterruptedException was thrown.");
1446        }
1447        assertEquals(4, counter);
1448
1449        st = new Thread() {
1450            public void run() {
1451                try {
1452                    sleep(10000);
1453                    fail("InterruptedException is thrown.");
1454                } catch(InterruptedException ie) {
1455                    //exception
1456                }
1457            }
1458        };
1459
1460        st.start();
1461        st.interrupt();
1462    }
1463
1464    /**
1465     * @tests java.lang.Thread#sleep(long, int)
1466     */
1467    @TestTargetNew(
1468        level = TestLevel.COMPLETE,
1469        notes = "",
1470        method = "sleep",
1471        args = {long.class, int.class}
1472    )
1473    public void test_sleepJI() {
1474        // Test for method void java.lang.Thread.sleep(long, int)
1475
1476        // TODO : Test needs revisiting.
1477        long stime = 0, ftime = 0;
1478        try {
1479            stime = System.currentTimeMillis();
1480            Thread.sleep(1000, 999999);
1481            ftime = System.currentTimeMillis();
1482        } catch (InterruptedException e) {
1483            fail("Unexpected interrupt received");
1484        }
1485        long result = ftime - stime;
1486        assertTrue("Failed to sleep long enough: " + result, result >= 900
1487                && result <= 1100);
1488
1489        counter = 0;
1490        st = new Thread() {
1491
1492            public void run() {
1493                while(true) {
1494                    try {
1495                        sleep(0, 999999);
1496                        counter++;
1497                    } catch(InterruptedException e) {
1498
1499                    }
1500                }
1501            }
1502        };
1503
1504        st.start();
1505
1506        try {
1507            Thread.sleep(2, 999999);
1508        } catch(InterruptedException e) {
1509            fail("InterruptedException was thrown.");
1510        }
1511        assertEquals(2, counter);
1512
1513        st = new Thread() {
1514            public void run() {
1515                try {
1516                    sleep(10000, 999999);
1517                    fail("InterruptedException is thrown.");
1518                } catch(InterruptedException ie) {
1519                    //exception
1520                }
1521            }
1522        };
1523        st.start();
1524        st.interrupt();
1525    }
1526
1527    /**
1528     * @tests java.lang.Thread#start()
1529     */
1530    @TestTargetNew(
1531        level = TestLevel.COMPLETE,
1532        notes = "",
1533        method = "start",
1534        args = {}
1535    )
1536    public void test_start() {
1537        // Test for method void java.lang.Thread.start()
1538        try {
1539            ResSupThread t = new ResSupThread(Thread.currentThread());
1540            synchronized (t) {
1541                ct = new Thread(t, "Interrupt Test4");
1542                ct.start();
1543                t.wait();
1544            }
1545            assertTrue("Thread is not running1", ct.isAlive());
1546            // Let the child thread get going.
1547            int orgval = t.getCheckVal();
1548            Thread.sleep(150);
1549            assertTrue("Thread is not running2", orgval != t.getCheckVal());
1550            ct.interrupt();
1551        } catch (InterruptedException e) {
1552            fail("Unexpected interrupt occurred");
1553        }
1554        Thread thr = new Thread();
1555        thr.start();
1556        try {
1557            thr.start();
1558        } catch(IllegalThreadStateException itse){
1559            //expected
1560        }
1561    }
1562
1563    /**
1564     * @tests java.lang.Thread#stop()
1565     */
1566    @TestTargetNew(
1567        level = TestLevel.COMPLETE,
1568        notes = "",
1569        method = "stop",
1570        args = {}
1571    )
1572    @AndroidOnly("Android throws UnsupportedOperationException for Thread.stop()")
1573    @SuppressWarnings("deprecation")
1574    public void test_stop() {
1575        // Test for method void java.lang.Thread.stop()
1576        try {
1577            Runnable r = new ResSupThread(null);
1578            synchronized (r) {
1579                st = new Thread(r, "Interupt Test5");
1580                st.start();
1581                r.wait();
1582            }
1583
1584        } catch (InterruptedException e) {
1585            fail("Unexpected interrupt received");
1586        }
1587        try {
1588            st.stop();
1589//            fail("Expected UnsupportedOperationException because" +
1590//                    "Thread.stop is not supported.");
1591        } catch (UnsupportedOperationException e) {
1592            // expected
1593        }
1594
1595        // Security checks are made even though stop() is not supported.
1596        SecurityManager sm = new SecurityManager() {
1597            public void checkPermission(Permission perm) {
1598                if(perm.getName().equals("stopThread")) {
1599                    throw new SecurityException();
1600                }
1601            }
1602        };
1603        st = new Thread();
1604        SecurityManager oldSm = System.getSecurityManager();
1605        System.setSecurityManager(sm);
1606        try {
1607            st.stop();
1608            fail("Should throw SecurityException");
1609        } catch (SecurityException e) {
1610            // expected
1611        } finally {
1612            System.setSecurityManager(oldSm);
1613        }
1614    }
1615
1616    /**
1617     * @tests java.lang.Thread#stop(java.lang.Throwable)
1618     */
1619    @TestTargetNew(
1620        level = TestLevel.PARTIAL_COMPLETE,
1621        notes = "Verifies security.",
1622        method = "stop",
1623        args = {java.lang.Throwable.class}
1624    )
1625    @SuppressWarnings("deprecation")
1626    public void test_stopLjava_lang_Throwable_subtest0() {
1627        // Security checks are made even though stop(Throwable) is not supported.
1628        Thread t = new Thread("t");
1629        class MySecurityManager extends SecurityManager {
1630            @Override
1631            public void checkAccess(Thread t) {
1632               throw new SecurityException();
1633            }
1634            @Override
1635            public void checkPermission(Permission permission) {
1636
1637                if(permission.getName().equals("stopThread")) {
1638                    throw new SecurityException();
1639                }
1640            }
1641        }
1642        MySecurityManager sm = new MySecurityManager();
1643        System.setSecurityManager(sm);
1644        try {
1645            try {
1646                t.stop(new ThreadDeath());
1647                fail("SecurityException was thrown.");
1648            } catch (SecurityException e) {
1649            }
1650            t.start();
1651            try {
1652                t.join(1000);
1653            } catch (InterruptedException e) {
1654            }
1655            try {
1656                t.stop(new ThreadDeath());
1657                fail("SecurityException was thrown.");
1658            } catch (SecurityException e) {
1659            }
1660
1661        } finally {
1662            System.setSecurityManager(null);
1663        }
1664    }
1665
1666    /**
1667     * @tests java.lang.Thread#stop(java.lang.Throwable)
1668     */
1669    @TestTargetNew(
1670        level = TestLevel.PARTIAL_COMPLETE,
1671        notes = "SecurityException is not verified.",
1672        method = "stop",
1673        args = {java.lang.Throwable.class}
1674    )
1675    @AndroidOnly("Android throws UnsupportedOperationException for Thread.stop(Thorwable)")
1676    @SuppressWarnings("deprecation")
1677    public void test_stopLjava_lang_Throwable() {
1678        // Test for method void java.lang.Thread.stop(java.lang.Throwable)
1679        ResSupThread t = new ResSupThread(Thread.currentThread());
1680        synchronized (t) {
1681            st = new Thread(t, "StopThread");
1682            st.setPriority(Thread.MAX_PRIORITY);
1683            st.start();
1684            try {
1685                t.wait();
1686            } catch (InterruptedException e) {
1687            }
1688        }
1689        try {
1690            st.stop(new BogusException("Bogus"));
1691//            fail("Expected UnsupportedOperationException because" +
1692//                    "Thread.stop is not supported.");
1693        } catch (UnsupportedOperationException e) {
1694            // expected
1695        }
1696
1697        try {
1698            st.stop(null);
1699            fail("Expected NullPointerException was not thrown");
1700        } catch (NullPointerException e) {
1701            // expected
1702        }
1703    }
1704
1705    /**
1706     * @tests java.lang.Thread#suspend()
1707     */
1708    @TestTargetNew(
1709        level = TestLevel.COMPLETE,
1710        notes = "",
1711        method = "suspend",
1712        args = {}
1713    )
1714    @AndroidOnly("Android throws UnsupportedOperationException for Thread.suspend()")
1715    @SuppressWarnings("deprecation")
1716    public void test_suspend() {
1717        // Test for method void java.lang.Thread.suspend()
1718        int orgval;
1719        ResSupThread t = new ResSupThread(Thread.currentThread());
1720        try {
1721            synchronized (t) {
1722                ct = new Thread(t, "Interupt Test6");
1723                ct.start();
1724                t.wait();
1725            }
1726            ct.suspend();
1727//            fail("Expected UnsupportedOperationException because" +
1728//                    "Thread.suspend is not supported.");
1729        } catch (UnsupportedOperationException e) {
1730            // expected
1731        } catch (InterruptedException e) {
1732            fail("Unexpected InterruptedException was thrown");
1733        }
1734
1735        // Security checks are made even though suspend() is not supported.
1736        SecurityManager sm = new SecurityManager() {
1737            public void checkPermission(Permission perm) {
1738            }
1739
1740            public void checkAccess(Thread t) {
1741                throw new SecurityException();
1742            }
1743        };
1744        st = new Thread();
1745        SecurityManager oldSm = System.getSecurityManager();
1746        System.setSecurityManager(sm);
1747        try {
1748            st.suspend();
1749            fail("Should throw SecurityException");
1750        } catch (SecurityException e) {
1751            // expected
1752        } finally {
1753            System.setSecurityManager(oldSm);
1754        }
1755    }
1756
1757    /**
1758     * @tests java.lang.Thread#toString()
1759     */
1760    @TestTargetNew(
1761        level = TestLevel.COMPLETE,
1762        notes = "",
1763        method = "toString",
1764        args = {}
1765    )
1766    public void test_toString() {
1767        // Test for method java.lang.String java.lang.Thread.toString()
1768        ThreadGroup tg = new ThreadGroup("Test Group5");
1769        st = new Thread(tg, new SimpleThread(1), "SimpleThread17");
1770        final String stString = st.toString();
1771        final String expected = "Thread[SimpleThread17,5,Test Group5]";
1772        assertTrue("Returned incorrect string: " + stString + "\t(expecting :"
1773                + expected + ")", stString.equals(expected));
1774        st.start();
1775        try {
1776            st.join();
1777        } catch (InterruptedException e) {
1778        }
1779        tg.destroy();
1780    }
1781
1782    @TestTargetNew(
1783        level = TestLevel.COMPLETE,
1784        notes = "",
1785        method = "yield",
1786        args = {}
1787    )
1788    public void test_yield() {
1789
1790        Counter [] countersNotYeld = new Counter[10];
1791
1792        for(int i = 0; i < 10; i++) {
1793            countersNotYeld[i] = new Counter(false);
1794        }
1795        Counter countersYeld = new Counter(true);
1796        try {
1797            Thread.sleep(11000);
1798        } catch(InterruptedException ie) {}
1799
1800        for(Counter c:countersNotYeld) {
1801            assertTrue(countersYeld.counter == c.counter);
1802        }
1803    }
1804
1805    class Counter extends Thread {
1806        public int counter = 0;
1807        boolean isDoYield = false;
1808
1809        public Counter(boolean isDoYield) {
1810            this.isDoYield = isDoYield;
1811            start();
1812        }
1813
1814        public void run() {
1815            for(int i = 0; i < 10000; i++) {
1816                if(isDoYield)
1817                    yield();
1818                counter ++;
1819            }
1820        }
1821    }
1822
1823
1824    /**
1825     * @tests java.lang.Thread#getAllStackTraces()
1826     */
1827    @TestTargetNew(
1828        level = TestLevel.COMPLETE,
1829        notes = "",
1830        method = "getAllStackTraces",
1831        args = {}
1832    )
1833    public void test_getAllStackTraces() {
1834        Map<Thread, StackTraceElement[]> stMap = Thread.getAllStackTraces();
1835        assertNotNull(stMap);
1836        //TODO add security-based tests
1837
1838        SecurityManager sm = new SecurityManager() {
1839
1840            public void checkPermission(Permission perm) {
1841                if(perm.getName().equals("modifyThreadGroup")) {
1842                    throw new SecurityException();
1843                }
1844            }
1845        };
1846
1847        SecurityManager oldSm = System.getSecurityManager();
1848        System.setSecurityManager(sm);
1849        try {
1850            Thread.getAllStackTraces();
1851            fail("Should throw SecurityException");
1852        } catch (SecurityException e) {
1853            // expected
1854        } finally {
1855           System.setSecurityManager(oldSm);
1856        }
1857    }
1858
1859    /**
1860     * @tests java.lang.Thread#getDefaultUncaughtExceptionHandler
1861     * @tests java.lang.Thread#setDefaultUncaughtExceptionHandler
1862     */
1863    @TestTargets({
1864        @TestTargetNew(
1865            level = TestLevel.COMPLETE,
1866            notes = "",
1867            method = "setDefaultUncaughtExceptionHandler",
1868            args = {java.lang.Thread.UncaughtExceptionHandler.class}
1869        ),
1870        @TestTargetNew(
1871            level = TestLevel.COMPLETE,
1872            notes = "",
1873            method = "getDefaultUncaughtExceptionHandler",
1874            args = {}
1875        )
1876    })
1877    public void test_get_setDefaultUncaughtExceptionHandler() {
1878        class Handler implements UncaughtExceptionHandler {
1879            public void uncaughtException(Thread thread, Throwable ex) {
1880            }
1881        }
1882
1883        final Handler handler = new Handler();
1884        Thread.setDefaultUncaughtExceptionHandler(handler);
1885        assertSame(handler, Thread.getDefaultUncaughtExceptionHandler());
1886
1887        Thread.setDefaultUncaughtExceptionHandler(null);
1888        assertNull(Thread.getDefaultUncaughtExceptionHandler());
1889        //TODO add security-based tests
1890
1891        SecurityManager sm = new SecurityManager() {
1892
1893            public void checkPermission(Permission perm) {
1894                if(perm.getName().
1895                        equals("setDefaultUncaughtExceptionHandler")) {
1896                    throw new SecurityException();
1897                }
1898            }
1899        };
1900
1901        SecurityManager oldSm = System.getSecurityManager();
1902        System.setSecurityManager(sm);
1903        try {
1904            st.setDefaultUncaughtExceptionHandler(handler);
1905            fail("Should throw SecurityException");
1906        } catch (SecurityException e) {
1907            // expected
1908        }  finally {
1909            System.setSecurityManager(oldSm);
1910        }
1911    }
1912
1913    /**
1914     * @tests java.lang.Thread#getStackTrace()
1915     */
1916    @TestTargetNew(
1917        level = TestLevel.COMPLETE,
1918        notes = "",
1919        method = "getStackTrace",
1920        args = {}
1921    )
1922    public void test_getStackTrace() {
1923        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
1924
1925        assertNotNull(stackTrace);
1926
1927        stack_trace_loop: {
1928            for (int i = 0; i < stackTrace.length; i++) {
1929                StackTraceElement e = stackTrace[i];
1930                if (getClass().getName().equals(e.getClassName())) {
1931                    if ("test_getStackTrace".equals(e.getMethodName())) {
1932                        break stack_trace_loop;
1933                    }
1934                }
1935            }
1936            fail("class and method not found in stack trace");
1937        }
1938
1939        //TODO add security-based tests
1940
1941        SecurityManager sm = new SecurityManager() {
1942
1943            public void checkPermission(Permission perm) {
1944                if(perm.getName().
1945                        equals("getStackTrace")) {
1946                    throw new SecurityException();
1947                }
1948            }
1949        };
1950        st = new Thread();
1951        SecurityManager oldSm = System.getSecurityManager();
1952        System.setSecurityManager(sm);
1953        try {
1954            st.getStackTrace();
1955            fail("Should throw SecurityException");
1956        } catch (SecurityException e) {
1957            // expected
1958        }  finally {
1959            System.setSecurityManager(oldSm);
1960        }
1961    }
1962
1963    /**
1964     * @tests java.lang.Thread#getState()
1965     */
1966    @TestTargetNew(
1967        level = TestLevel.COMPLETE,
1968        notes = "",
1969        method = "getState",
1970        args = {}
1971    )
1972    public void test_getState() {
1973        Thread.State state = Thread.currentThread().getState();
1974        assertNotNull(state);
1975        assertEquals(Thread.State.RUNNABLE, state);
1976
1977        final Semaphore sem = new Semaphore(0);
1978        final Object lock = new Object();
1979        Thread th = new Thread() {
1980            @Override
1981            public void run() {
1982                  while (!sem.hasQueuedThreads()) {}
1983                  sem.release();
1984                  while (run) {}
1985                  try {
1986                      sem.acquire();
1987                  } catch (InterruptedException e) {
1988                      fail("InterruptedException was thrown.");
1989                  }
1990                  synchronized (lock) {
1991                      lock.equals(new Object());
1992                  }
1993                  synchronized (lock) {
1994                      try {
1995                        sem.release();
1996                        lock.wait(Long.MAX_VALUE);
1997                      } catch (InterruptedException e) {
1998                          // expected
1999                      }
2000                  }
2001            }
2002        };
2003        assertEquals(Thread.State.NEW, th.getState());
2004        th.start();
2005        try {
2006            sem.acquire();
2007        } catch (InterruptedException e) {
2008            fail("InterruptedException was thrown.");
2009        }
2010        assertEquals(Thread.State.RUNNABLE, th.getState());
2011        run = false;
2012
2013        while (!sem.hasQueuedThreads()){}
2014
2015        assertEquals(Thread.State.WAITING, th.getState());
2016        synchronized (lock) {
2017            sem.release();
2018            long start = System.currentTimeMillis();
2019            while(start + 1000 > System.currentTimeMillis()) {}
2020            assertEquals(Thread.State.BLOCKED, th.getState());
2021        }
2022
2023        try {
2024            sem.acquire();
2025        } catch (InterruptedException e) {
2026            fail("InterruptedException was thrown.");
2027        }
2028
2029        synchronized (lock) {
2030            assertEquals(Thread.State.TIMED_WAITING, th.getState());
2031            th.interrupt();
2032        }
2033
2034        try {
2035            th.join(1000);
2036        } catch(InterruptedException ie) {
2037            fail("InterruptedException was thrown.");
2038        }
2039        assertEquals(Thread.State.TERMINATED, th.getState());
2040    }
2041    boolean run = true;
2042
2043    /**
2044     * @tests java.lang.Thread#getUncaughtExceptionHandler
2045     * @tests java.lang.Thread#setUncaughtExceptionHandler
2046     */
2047    @TestTargets({
2048        @TestTargetNew(
2049            level = TestLevel.COMPLETE,
2050            notes = "",
2051            method = "getUncaughtExceptionHandler",
2052            args = {}
2053        ),
2054        @TestTargetNew(
2055            level = TestLevel.COMPLETE,
2056            notes = "",
2057            method = "setUncaughtExceptionHandler",
2058            args = {java.lang.Thread.UncaughtExceptionHandler.class}
2059        )
2060    })
2061    public void test_get_setUncaughtExceptionHandler() {
2062        class Handler implements UncaughtExceptionHandler {
2063            public void uncaughtException(Thread thread, Throwable ex) {
2064            }
2065        }
2066
2067        final Handler handler = new Handler();
2068        Thread.currentThread().setUncaughtExceptionHandler(handler);
2069        assertSame(handler, Thread.currentThread().getUncaughtExceptionHandler());
2070
2071        Thread.currentThread().setUncaughtExceptionHandler(null);
2072
2073        //TODO add security-based tests
2074        SecurityManager sm = new SecurityManager() {
2075
2076            public void checkPermission(Permission perm) {
2077            }
2078
2079            public void checkAccess(Thread t) {
2080               throw new SecurityException();
2081            }
2082        };
2083        st = new Thread();
2084        SecurityManager oldSm = System.getSecurityManager();
2085        System.setSecurityManager(sm);
2086        try {
2087            st.setUncaughtExceptionHandler(handler);
2088            fail("Should throw SecurityException");
2089        } catch (SecurityException e) {
2090            // expected
2091        } finally {
2092            System.setSecurityManager(oldSm);
2093        }
2094
2095    }
2096
2097    /**
2098     * @tests java.lang.Thread#getId()
2099     */
2100    @TestTargetNew(
2101        level = TestLevel.COMPLETE,
2102        notes = "",
2103        method = "getId",
2104        args = {}
2105    )
2106    public void test_getId() {
2107        assertTrue("current thread's ID is not positive", Thread.currentThread().getId() > 0);
2108
2109        //check all the current threads for positive IDs
2110        Map<Thread, StackTraceElement[]> stMap = Thread.getAllStackTraces();
2111        for (Thread thread : stMap.keySet()) {
2112            assertTrue("thread's ID is not positive: " + thread.getName(), thread.getId() > 0);
2113        }
2114    }
2115
2116    /**
2117     * @tests java.lang.Thread#holdLock()
2118     */
2119    @TestTargetNew(
2120        level = TestLevel.COMPLETE,
2121        notes = "",
2122        method = "holdsLock",
2123        args = {java.lang.Object.class}
2124    )
2125    public void test_holdsLock() {
2126        MonitoredClass monitor = new MonitoredClass();
2127
2128        monitor.enterLocked();
2129        monitor.enterNonLocked();
2130
2131        try {
2132            Thread.holdsLock(null);
2133            fail("NullPointerException was not thrown.");
2134        } catch(NullPointerException npe) {
2135            //expected
2136        }
2137    }
2138
2139    @Override
2140    protected void tearDown() {
2141        try {
2142            if (st != null)
2143                st.interrupt();
2144        } catch (Exception e) {
2145        }
2146        try {
2147            if (spinner != null)
2148                spinner.interrupt();
2149        } catch (Exception e) {
2150        }
2151        try {
2152            if (ct != null)
2153                ct.interrupt();
2154        } catch (Exception e) {
2155        }
2156
2157        try {
2158            spinner = null;
2159            st = null;
2160            ct = null;
2161            System.runFinalization();
2162        } catch (Exception e) {
2163        }
2164    }
2165}
2166