0001: /*
0002: * Licensed to the Apache Software Foundation (ASF) under one or more
0003: * contributor license agreements. See the NOTICE file distributed with
0004: * this work for additional information regarding copyright ownership.
0005: * The ASF licenses this file to You under the Apache License, Version 2.0
0006: * (the "License"); you may not use this file except in compliance with
0007: * the License. You may obtain a copy of the License at
0008: *
0009: * http://www.apache.org/licenses/LICENSE-2.0
0010: *
0011: * Unless required by applicable law or agreed to in writing, software
0012: * distributed under the License is distributed on an "AS IS" BASIS,
0013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014: * See the License for the specific language governing permissions and
0015: * limitations under the License.
0016: */
0017:
0018: package java.lang;
0019:
0020: import junit.framework.TestCase;
0021:
0022: import java.util.Map;
0023: import java.util.Set;
0024: import org.apache.harmony.test.ReversibleSecurityManager;
0025:
0026: /**
0027: * This class provides an implementation of J2SE v. 1.5 API Specification of
0028: * unit.java.lang.ThreadTest class.
0029: */
0030: public class ThreadTest extends TestCase {
0031:
0032: private static final String INTERRUPTED_MESSAGE = "thread has been unexpectedly interrupted";
0033:
0034: // max time interval to wait for some events in ms
0035: private static final long waitDuration = 60000;
0036:
0037: // waiting time for some event
0038: private long waitTime = 0;
0039:
0040: private boolean expired;
0041: private SecurityManager sm = null;
0042:
0043: private enum Action {
0044: WAIT, SLEEP, JOIN
0045: }
0046:
0047: private class RunProject extends Thread {
0048: private Team team;
0049:
0050: RunProject(Team t) {
0051: this .team = t;
0052: }
0053:
0054: public void run() {
0055: team.work();
0056: }
0057: }
0058:
0059: private class Team {
0060: public volatile int i = 0;
0061: volatile boolean stopProject = false;
0062:
0063: public synchronized void work() {
0064: while (!stopProject) {
0065: i++;
0066: }
0067: }
0068:
0069: public void stopWork() {
0070: stopProject = true;
0071: }
0072: }
0073:
0074: private class TestThread extends Thread {
0075:
0076: public InterruptedException e = null;
0077:
0078: public void run() {
0079: try {
0080: synchronized (this ) {
0081: this .notify();
0082: this .wait();
0083: }
0084: } catch (InterruptedException e) {
0085: this .e = e;
0086: }
0087: }
0088: }
0089:
0090: static class ThreadRunning extends Thread {
0091: volatile boolean stopWork = false;
0092: long startTime;
0093: public volatile int i = 0;
0094:
0095: ThreadRunning() {
0096: super ();
0097: }
0098:
0099: ThreadRunning(String name) {
0100: super (name);
0101: }
0102:
0103: ThreadRunning(Runnable target, String name) {
0104: super (target, name);
0105: }
0106:
0107: ThreadRunning(ThreadGroup g, String name) {
0108: super (g, name);
0109: }
0110:
0111: ThreadRunning(ThreadGroup g, Runnable target) {
0112: super (g, target);
0113: }
0114:
0115: ThreadRunning(ThreadGroup g, Runnable target, String name) {
0116: super (g, target, name);
0117: }
0118:
0119: public void run() {
0120: startTime = System.currentTimeMillis();
0121: while (!stopWork) {
0122: i++;
0123: }
0124: }
0125:
0126: public long getStartTime() {
0127: return startTime;
0128: }
0129: }
0130:
0131: private class ThreadWaiting extends Thread {
0132: public volatile boolean started = false;
0133: private long millis;
0134: private int nanos;
0135: private Action action;
0136: private boolean exceptionReceived = false;
0137: private long startTime;
0138: private long endTime;
0139: private Object lock;
0140:
0141: ThreadWaiting(Action action, long millis, int nanos, Object lock) {
0142: this .millis = millis;
0143: this .nanos = nanos;
0144: this .action = action;
0145: this .lock = lock;
0146: }
0147:
0148: public void run() {
0149: switch (action) {
0150: case WAIT:
0151: synchronized (lock) {
0152: this .started = true;
0153: lock.notify();
0154: }
0155: synchronized (this ) {
0156: try {
0157: this .wait(millis, nanos);
0158: } catch (InterruptedException e) {
0159: exceptionReceived = true;
0160: }
0161: }
0162: case SLEEP:
0163: try {
0164: synchronized (lock) {
0165: started = true;
0166: lock.notify();
0167: }
0168: this .startTime = System.currentTimeMillis();
0169: Thread.sleep(millis, nanos);
0170: this .endTime = System.currentTimeMillis();
0171: } catch (InterruptedException e) {
0172: exceptionReceived = true;
0173: }
0174: case JOIN:
0175: try {
0176: synchronized (lock) {
0177: started = true;
0178: lock.notify();
0179: }
0180: this .join(millis, nanos);
0181: } catch (InterruptedException e) {
0182: exceptionReceived = true;
0183: }
0184: }
0185: }
0186:
0187: public long getStartTime() {
0188: return startTime;
0189: }
0190:
0191: public long getEndTime() {
0192: return endTime;
0193: }
0194: }
0195:
0196: private class ThreadRunningAnotherThread extends Thread {
0197: int field = 0;
0198: volatile boolean stop = false;
0199: boolean childIsDaemon = false;
0200: Thread curThread = null;
0201:
0202: public ThreadRunningAnotherThread() {
0203: super ();
0204: }
0205:
0206: public ThreadRunningAnotherThread(String name) {
0207: super (name);
0208: }
0209:
0210: public void run() {
0211: Thread child = new Thread();
0212: curThread = Thread.currentThread();
0213: childIsDaemon = child.isDaemon();
0214: while (!stop) {
0215: field++;
0216: }
0217: }
0218: }
0219:
0220: private static class ThreadYielding extends Thread {
0221: private int item;
0222: public static final int dim = 200;
0223: public static int list[] = new int[dim];
0224: private static int index = 0;
0225:
0226: public ThreadYielding(int item) {
0227: this .item = item;
0228: }
0229:
0230: private static synchronized int getNextIndex() {
0231: return index++;
0232: }
0233:
0234: public synchronized void setItem() {
0235: list[getNextIndex()] = this .item;
0236: }
0237:
0238: public void run() {
0239: for (int i = 0; i < dim / 2; i++) {
0240: setItem();
0241: Thread.yield();
0242: }
0243: }
0244: }
0245:
0246: class Square implements Runnable {
0247: volatile boolean stop = false;
0248: boolean once;
0249: int number;
0250: int squaredNumber;
0251:
0252: Square(int number) {
0253: this (number, false);
0254: }
0255:
0256: Square(int number, boolean once) {
0257: this .number = number;
0258: this .once = once;
0259: }
0260:
0261: public void run() {
0262: while (!stop) {
0263: squaredNumber = number * number;
0264: if (once) {
0265: break;
0266: }
0267: }
0268: }
0269: }
0270:
0271: /**
0272: * Sleep for "interval" ms
0273: * @return true if waitTime is up
0274: */
0275: private boolean doSleep(int interval) {
0276: try {
0277: Thread.sleep(interval);
0278: } catch (InterruptedException e) {
0279: fail("unexpected InterruptedException while sleeping");
0280: }
0281: waitTime -= interval;
0282: return waitTime <= 0;
0283: }
0284:
0285: /**
0286: * Verify that the toString() method displays the thread's name,
0287: * priority and thread group.
0288: */
0289: public void testToString() {
0290: Thread t = new Thread();
0291: String info = t.toString();
0292: String name = t.getName();
0293: assertTrue("thread's name is not displayed",
0294: info.indexOf(name) >= 0);
0295: String stringPriority = new Integer(t.getPriority()).toString();
0296: assertTrue("thread's priority is not displayed", info
0297: .indexOf("," + stringPriority + ",") > 0);
0298: String groupName = t.getThreadGroup().getName();
0299: assertTrue("thread's group is not displayed", info
0300: .indexOf(groupName) > 0);
0301: }
0302:
0303: /**
0304: * Thread()
0305: */
0306: public void testThread() {
0307: Thread t = new Thread();
0308: assertTrue("incorrect thread name", t.toString().indexOf(
0309: "Thread-") >= 0);
0310: assertSame("incorrect thread group", Thread.currentThread()
0311: .getThreadGroup(), t.getThreadGroup());
0312: }
0313:
0314: /**
0315: * Verify that a thread created by a daemon thread is daemon
0316: */
0317: public void testThread_Daemon() {
0318: ThreadRunningAnotherThread t = new ThreadRunningAnotherThread();
0319: t.setDaemon(true);
0320: t.start();
0321: t.stop = true;
0322: try {
0323: t.join();
0324: } catch (InterruptedException e) {
0325: fail(INTERRUPTED_MESSAGE);
0326: }
0327: assertTrue("the child thread of a daemon thread is non-daemon",
0328: t.childIsDaemon);
0329: }
0330:
0331: /**
0332: * Verify that a thread created by a non-daemon thread is not daemon
0333: */
0334: public void testThread_NotDaemon() {
0335: ThreadRunningAnotherThread t = new ThreadRunningAnotherThread();
0336: t.setDaemon(false);
0337: t.start();
0338: t.stop = true;
0339: try {
0340: t.join();
0341: } catch (InterruptedException e) {
0342: fail(INTERRUPTED_MESSAGE);
0343: }
0344: assertFalse(
0345: "the child thread of a non-daemon thread is daemon",
0346: t.childIsDaemon);
0347: }
0348:
0349: /**
0350: * Thread(Runnable)
0351: */
0352: public void testThreadRunnable() {
0353: Square s = new Square(25);
0354: Thread t = new Thread(s);
0355: t.start();
0356: waitTime = waitDuration;
0357: while (s.squaredNumber == 0 && !(expired = doSleep(10))) {
0358: }
0359: assertEquals("incorrect thread name", 0, t.getName().indexOf(
0360: "Thread-"));
0361: assertSame("incorrect thread group", Thread.currentThread()
0362: .getThreadGroup(), t.getThreadGroup());
0363: s.stop = true;
0364: assertEquals("thread has not run", 625, s.squaredNumber);
0365: }
0366:
0367: /**
0368: * Thread(Runnable, String)
0369: */
0370: public void testThreadRunnableString() {
0371: Square s = new Square(25);
0372: String name = "squaring";
0373: Thread t = new Thread(s, name);
0374: t.start();
0375: waitTime = waitDuration;
0376: while (s.squaredNumber == 0 && !(expired = doSleep(10))) {
0377: }
0378: assertEquals("incorrect thread name", name, t.getName());
0379: assertSame("incorrect thread group", Thread.currentThread()
0380: .getThreadGroup(), t.getThreadGroup());
0381: s.stop = true;
0382: assertEquals("thread has not run", 625, s.squaredNumber);
0383: }
0384:
0385: /**
0386: * Thread(Runnable, String)
0387: */
0388: public void testThreadRunnableString_NullNotNull() {
0389: String name = "newThread";
0390: ThreadRunning t = new ThreadRunning((Runnable) null, name);
0391: assertEquals("incorrect thread name", name, t.getName());
0392: assertSame("incorrect thread group", Thread.currentThread()
0393: .getThreadGroup(), t.getThreadGroup());
0394: t.start();
0395: // thread's run() method should be called if Runnable==null
0396: waitTime = waitDuration;
0397: while (t.i == 0 && !(expired = doSleep(10))) {
0398: }
0399: t.stopWork = true;
0400: assertTrue("thread's run() method has not started", t.i != 0);
0401: }
0402:
0403: /**
0404: * Thread(String)
0405: */
0406: public void testThreadString() {
0407: String name = "threadString";
0408: Thread t = new Thread(name);
0409: assertTrue("incorrect thread name",
0410: t.toString().indexOf(name) >= 0);
0411: assertSame("incorrect thread group", Thread.currentThread()
0412: .getThreadGroup(), t.getThreadGroup());
0413: }
0414:
0415: /**
0416: * Verify creating a thread with the null name.
0417: * NullPointerException should be thrown.
0418: */
0419: public void testThreadStringNull() {
0420: String threadName = null;
0421: try {
0422: new Thread(threadName);
0423: fail("NullPointerException should be thrown when creating "
0424: + "a thread with null name");
0425: } catch (NullPointerException e) {
0426: return;
0427: }
0428: }
0429:
0430: /**
0431: * Thread(ThreadGroup, Runnable)
0432: */
0433: public void testThreadThreadGroupRunnable() {
0434: Square s = new Square(25);
0435: ThreadGroup tg = new ThreadGroup("newGroup");
0436: Thread t = new Thread(tg, s);
0437: t.start();
0438: waitTime = waitDuration;
0439: while (s.squaredNumber == 0 && !(expired = doSleep(10))) {
0440: }
0441: assertEquals("incorrect thread name", 0, t.getName().indexOf(
0442: "Thread-"));
0443: assertSame("incorrect thread group", tg, t.getThreadGroup());
0444: s.stop = true;
0445: assertEquals("thread has not run", 625, s.squaredNumber);
0446: }
0447:
0448: /**
0449: * Thread(ThreadGroup, Runnable) where both arguments are null
0450: */
0451: public void testThreadThreadGroupRunnable_NullNull() {
0452: ThreadRunning t = new ThreadRunning((ThreadGroup) null,
0453: (Runnable) null);
0454: assertEquals("incorrect thread name", 0, t.getName().indexOf(
0455: "Thread-"));
0456: assertSame("incorrect thread group", Thread.currentThread()
0457: .getThreadGroup(), t.getThreadGroup());
0458: t.start();
0459: // thread's run() method should be called if Runnable==null
0460: waitTime = waitDuration;
0461: while (t.i == 0 && !(expired = doSleep(10))) {
0462: }
0463: t.stopWork = true;
0464: assertTrue("thread's run() method has not started", t.i != 0);
0465: }
0466:
0467: /**
0468: * Thread(ThreadGroup, Runnable, String)
0469: */
0470: public void testThreadThreadGroupRunnableString() {
0471: ThreadGroup tg = new ThreadGroup("newGroup");
0472: String name = "t1";
0473: Square s = new Square(25);
0474: Thread t = new Thread(tg, s, name);
0475: t.start();
0476: waitTime = waitDuration;
0477: while (s.squaredNumber == 0 && !(expired = doSleep(10))) {
0478: }
0479: assertEquals("incorrect thread name", 0, t.getName().indexOf(
0480: name));
0481: assertSame("incorrect thread group", tg, t.getThreadGroup());
0482: s.stop = true;
0483: assertEquals("thread has not run", 625, s.squaredNumber);
0484: }
0485:
0486: /**
0487: * Thread(ThreadGroup, Runnable, String) where all arguments are null
0488: */
0489: public void testThreadThreadGroupRunnableString_NullNullNull() {
0490: try {
0491: new Thread(null, null, null);
0492: fail("NullPointerException has not been thrown");
0493: } catch (NullPointerException e) {
0494: return;
0495: }
0496: }
0497:
0498: /**
0499: * Thread(ThreadGroup, Runnable, String) where both
0500: * ThreadGroup and Runnable are null
0501: */
0502: public void testThreadThreadGroupRunnableString_NullNullNotNull() {
0503: String name = "t1";
0504: ThreadRunning t1 = new ThreadRunning(null, null, name);
0505: assertSame("incorrect thread group", Thread.currentThread()
0506: .getThreadGroup(), t1.getThreadGroup());
0507: t1.start();
0508: // thread's run() method should be called if Runnable==null
0509: waitTime = waitDuration;
0510: while (t1.i == 0 && !(expired = doSleep(10))) {
0511: }
0512: t1.stopWork = true;
0513: assertTrue("thread's run() method has not started", t1.i != 0);
0514: }
0515:
0516: /**
0517: * Thread(ThreadGroup, Runnable, String) where ThreadGroup is null
0518: */
0519: public void testThreadThreadGroupRunnableString_NullNotNullNotNull() {
0520: String name = "t1";
0521: Square s = new Square(25);
0522: Thread t = new Thread(null, s, name);
0523: t.start();
0524: waitTime = waitDuration;
0525: while (s.squaredNumber == 0 && !(expired = doSleep(10))) {
0526: }
0527: assertEquals("incorrect thread name", 0, t.getName().indexOf(
0528: name));
0529: assertSame("incorrect thread group", Thread.currentThread()
0530: .getThreadGroup(), t.getThreadGroup());
0531: s.stop = true;
0532: assertEquals("thread has not run", 625, s.squaredNumber);
0533: }
0534:
0535: /**
0536: * Thread(ThreadGroup, Runnable, String, long)
0537: */
0538: public void testThreadThreadGroupRunnableStringlong() {
0539: ThreadGroup tg = new ThreadGroup("newGroup");
0540: String name = "t1";
0541: Square s = new Square(25);
0542: Thread t = new Thread(tg, s, name, 0);
0543: t.start();
0544: waitTime = waitDuration;
0545: StackTraceElement ste[] = t.getStackTrace();
0546: while (ste.length == 0 && !(expired = doSleep(10))) {
0547: ste = t.getStackTrace();
0548: }
0549: s.stop = true;
0550: if (expired) {
0551: fail("stack dump of thread t1 is empty");
0552: }
0553: }
0554:
0555: /**
0556: * Thread(ThreadGroup, Runnable, String, long)
0557: */
0558: public void testThreadThreadGroupRunnableStringlong_Long_MAX_VALUE() {
0559: ThreadGroup tg = new ThreadGroup("newGroup");
0560: String name = "t1";
0561: Square s = new Square(25);
0562: StackTraceElement ste[] = null;
0563: try {
0564: Thread t;
0565: try {
0566: t = new Thread(tg, s, name, Long.MAX_VALUE);
0567: } catch (OutOfMemoryError e) {
0568: // fall back to default stack size if can't allocate
0569: // Long.MAX_VALUE bytes for stack
0570: t = new Thread(tg, s, name, 0);
0571: }
0572: t.start();
0573: waitTime = waitDuration;
0574: ste = t.getStackTrace();
0575: while (ste.length == 0 && !(expired = doSleep(10))) {
0576: ste = t.getStackTrace();
0577: }
0578: s.stop = true;
0579: if (expired) {
0580: fail("stack dump of thread t1 is empty");
0581: }
0582: } catch (OutOfMemoryError er) {
0583: fail("OutOfMemoryError when stack size is Long.MAX_VALUE");
0584: }
0585: }
0586:
0587: /**
0588: * Thread(ThreadGroup, String)
0589: */
0590: public void testThreadThreadGroupString() {
0591: String name = "newThread";
0592: ThreadGroup tg = new ThreadGroup("newGroup");
0593: Thread t = new Thread(tg, name);
0594: assertEquals("incorrect thread name", name, t.getName());
0595: assertSame("incorrect thread group", tg, t.getThreadGroup());
0596: }
0597:
0598: /**
0599: * Get active threads count; should be > 0
0600: */
0601: public void testActiveCount() {
0602: int activeCount = Thread.activeCount();
0603: assertTrue("The active threads count must be >0.",
0604: activeCount > 0);
0605: }
0606:
0607: /**
0608: * Verify currentThread()
0609: */
0610: public void testCurrentThread() {
0611: String name = "runThread";
0612: ThreadRunningAnotherThread t = new ThreadRunningAnotherThread(
0613: name);
0614: t.start();
0615: waitTime = waitDuration;
0616: while (t.curThread == null && !(expired = doSleep(10))) {
0617: }
0618: assertEquals("incorect current thread name", name, t.curThread
0619: .getName());
0620: t.stop = true;
0621: }
0622:
0623: /**
0624: * Verify currentThread()
0625: */
0626: public void testCurrentThread_Main() {
0627: String name = "ain";
0628: Thread t = Thread.currentThread();
0629: assertTrue("incorect current thread name", t.getName().indexOf(
0630: name) > 0);
0631: }
0632:
0633: public void testEnumerate() {
0634: ThreadRunning t1 = new ThreadRunning("ttt1");
0635: t1.start();
0636: ThreadRunning t2 = new ThreadRunning("ttt2");
0637: t2.start();
0638: ThreadGroup tg1 = new ThreadGroup("tg1");
0639: ThreadRunning t11 = new ThreadRunning(tg1, "ttt11");
0640: t11.start();
0641: ThreadRunning t12 = new ThreadRunning(tg1, "ttt12");
0642: t12.start();
0643: ThreadGroup tg12 = new ThreadGroup(tg1, "tg12");
0644: ThreadRunning t121 = new ThreadRunning(tg12, "ttt121");
0645: t121.start();
0646: ThreadRunning t122 = new ThreadRunning(tg12, "ttt122");
0647: t122.start();
0648: // estimate dimension as 6 created threads
0649: // plus 10 for some other threads
0650: int estimateLength = 16;
0651: Thread list[];
0652: int count;
0653: while (true) {
0654: list = new Thread[estimateLength];
0655: count = Thread.enumerate(list);
0656: if (count == estimateLength) {
0657: estimateLength *= 2;
0658: } else {
0659: break;
0660: }
0661: }
0662: int enumerateCount = 0;
0663: for (int i = 0; i < count; i++) {
0664: if (list[i].toString().indexOf("ttt") > 0) {
0665: enumerateCount++;
0666: }
0667: }
0668: t1.stopWork = true;
0669: t2.stopWork = true;
0670: t11.stopWork = true;
0671: t12.stopWork = true;
0672: t121.stopWork = true;
0673: t122.stopWork = true;
0674: assertEquals("some threads are missed", 6, enumerateCount);
0675: }
0676:
0677: /**
0678: * Test for holdsLock(Object obj)
0679: */
0680: public void testHoldsLock_False() {
0681: Object lock = new Object();
0682: assertFalse("lock should not be held", Thread.holdsLock(lock));
0683: }
0684:
0685: /**
0686: * Test for holdsLock(Object obj)
0687: */
0688: public void testHoldsLock_True() {
0689: Object lock = new Object();
0690: synchronized (lock) {
0691: assertTrue("lock should be held", Thread.holdsLock(lock));
0692: try {
0693: Thread.sleep(100);
0694: } catch (InterruptedException e) {
0695: fail(INTERRUPTED_MESSAGE);
0696: }
0697: assertTrue("lock should be held after sleeping", Thread
0698: .holdsLock(lock));
0699: try {
0700: lock.wait(100);
0701: } catch (InterruptedException e) {
0702: fail(INTERRUPTED_MESSAGE);
0703: }
0704: assertTrue("lock should be obtained after waiting", Thread
0705: .holdsLock(lock));
0706: }
0707: assertFalse("lock should not be held", Thread.holdsLock(lock));
0708: }
0709:
0710: /**
0711: * Test for holdsLock(null)
0712: */
0713: public void testHoldsLock_Null() {
0714: try {
0715: Thread.holdsLock(null);
0716: fail("NullPointerException has not been thrown");
0717: } catch (NullPointerException e) {
0718: return;
0719: }
0720: }
0721:
0722: /**
0723: * Verify that interrupt status is cleared by the interrupted()
0724: */
0725: public void testInterrupted() {
0726: class ThreadInterrupt extends Thread {
0727: private boolean interrupted1 = false;
0728: private boolean interrupted2;
0729:
0730: public void run() {
0731: interrupt();
0732: interrupted1 = Thread.interrupted();
0733: interrupted2 = Thread.interrupted();
0734: }
0735: }
0736: ;
0737: ThreadInterrupt t = new ThreadInterrupt();
0738: t.start();
0739: for (waitTime = waitDuration; !t.interrupted1
0740: && !(expired = doSleep(10));) {
0741: }
0742: assertTrue("interrupt status has not changed to true",
0743: t.interrupted1);
0744: assertFalse("interrupt status has not changed to false",
0745: t.interrupted2);
0746: }
0747:
0748: /**
0749: * Test for void sleep(long)
0750: */
0751: public void testSleeplong() {
0752: Object lock = new Object();
0753: long millis = 2000;
0754: ThreadWaiting tW = new ThreadWaiting(Action.SLEEP, millis, 0,
0755: lock);
0756: try {
0757: synchronized (lock) {
0758: tW.start();
0759: while (!tW.started) {
0760: lock.wait();
0761: }
0762: }
0763: } catch (InterruptedException e) {
0764: fail(INTERRUPTED_MESSAGE);
0765: }
0766: try {
0767: tW.join();
0768: } catch (InterruptedException e) {
0769: fail(INTERRUPTED_MESSAGE);
0770: }
0771: long duration = tW.getEndTime() - tW.getStartTime();
0772: // we allow the test to wait 2.5% less
0773: long atLeast = millis - 50;
0774: assertTrue("thread has not slept enough: expected " + atLeast
0775: + " but was " + duration, duration >= atLeast);
0776: }
0777:
0778: /**
0779: * Test for void sleep(long, int)
0780: */
0781: public void testSleeplongint() {
0782: Object lock = new Object();
0783: long millis = 2000;
0784: int nanos = 123456;
0785: ThreadWaiting tW = new ThreadWaiting(Action.SLEEP, millis,
0786: nanos, lock);
0787: try {
0788: synchronized (lock) {
0789: tW.start();
0790: while (!tW.started) {
0791: lock.wait();
0792: }
0793: }
0794: } catch (InterruptedException e) {
0795: fail(INTERRUPTED_MESSAGE);
0796: }
0797: try {
0798: tW.join();
0799: } catch (InterruptedException e) {
0800: fail(INTERRUPTED_MESSAGE);
0801: }
0802: long duration = tW.getEndTime() - tW.getStartTime();
0803: duration *= 1000000; // nano
0804: // we allow the test to wait 2.5% less
0805: long atLeast = (millis - 50) * 1000000;
0806: assertTrue("thread has not slept enough: expected " + atLeast
0807: + " but was " + duration, duration >= atLeast);
0808: }
0809:
0810: /**
0811: * Test for void yield()
0812: */
0813: public void testYield() {
0814: ThreadYielding t1 = new ThreadYielding(1);
0815: ThreadYielding t2 = new ThreadYielding(2);
0816: t1.start();
0817: t2.start();
0818: try {
0819: t1.join();
0820: t2.join();
0821: } catch (InterruptedException e) {
0822: fail(INTERRUPTED_MESSAGE);
0823: }
0824: int oneCount = 0;
0825: int threadNum = ThreadYielding.dim;
0826: for (int i = 0; i < threadNum; i++) {
0827: if (ThreadYielding.list[i] == 1) {
0828: oneCount++;
0829: }
0830: }
0831: // We suppose that threads t1 and t2 alternate with each other.
0832: // The might be a case when some another thread (not t2) runs
0833: // while t1 is yelding. In this case the 'list' might start with 1s
0834: // and end with 2s and look like threads does not alternate.
0835: // We cannot treat this as failure nevertheless.
0836: // We just make sure that both threads have finished successfully.
0837: assertTrue("threads have not finished successfully",
0838: oneCount == threadNum / 2);
0839: }
0840:
0841: /**
0842: * Test for checkAccess when there is a SecurityManager
0843: */
0844: public void testCheckAccess() {
0845: SecurityManager sm = System.getSecurityManager();
0846: System.setSecurityManager(new ReversibleSecurityManager());
0847: Thread t = new Thread();
0848: try {
0849: t.checkAccess();
0850: } finally {
0851: System.setSecurityManager(sm);
0852: }
0853: }
0854:
0855: public void testDestroy() {
0856: Thread t = new Thread();
0857: try {
0858: t.destroy();
0859: fail("the destroy method should not be implemented");
0860: } catch (NoSuchMethodError er) {
0861: return;
0862: }
0863: }
0864:
0865: /**
0866: * Get context ClassLoader of a newly created thread
0867: */
0868: public void testGetContextClassLoader() {
0869: Thread t = new Thread();
0870: assertSame("improper ClassLoader", Thread.currentThread()
0871: .getContextClassLoader(), t.getContextClassLoader());
0872: }
0873:
0874: /**
0875: * Get context ClassLoader of main thread
0876: */
0877: public void testGetContextClassLoader_Main() {
0878: ClassLoader cl = null;
0879:
0880: // find the root ThreadGroup
0881: ThreadGroup parent = new ThreadGroup(Thread.currentThread()
0882: .getThreadGroup(), "Temporary");
0883: ThreadGroup newParent = parent.getParent();
0884: while (newParent != null) {
0885: parent = newParent;
0886: newParent = parent.getParent();
0887: }
0888:
0889: // enumerate threads and select "main" thread
0890: int threadsCount = parent.activeCount() + 1;
0891: int count;
0892: Thread[] liveThreads;
0893: while (true) {
0894: liveThreads = new Thread[threadsCount];
0895: count = parent.enumerate(liveThreads);
0896: if (count == threadsCount) {
0897: threadsCount *= 2;
0898: } else {
0899: break;
0900: }
0901: }
0902: for (int i = 0; i < count; i++) {
0903: if (liveThreads[i].toString().indexOf("ain]") > 0) {
0904: cl = liveThreads[i].getContextClassLoader();
0905: break;
0906: }
0907: }
0908: assertSame("improper ClassLoader", cl, ClassLoader
0909: .getSystemClassLoader());
0910: }
0911:
0912: /**
0913: * Check that IDs of different threads differ
0914: */
0915: public void testGetIdUnique() {
0916: Thread t1 = new Thread("thread1");
0917: Thread t2 = new Thread("thread2");
0918: assertTrue("Thread id must be unique", t1.getId() != t2.getId());
0919: }
0920:
0921: /**
0922: * Check that ID of a thread does not change
0923: */
0924: public void testGetIdUnchanged() {
0925: ThreadRunning t1 = new ThreadRunning();
0926: long tIdNew = t1.getId();
0927: t1.start();
0928: waitTime = waitDuration;
0929: while (t1.i == 0 && !(expired = doSleep(10))) {
0930: }
0931: if (expired) {
0932: fail("thread has not started");
0933: }
0934: long tIdRun = t1.getId();
0935: assertEquals("Thread ID after start should not change", tIdNew,
0936: tIdRun);
0937: t1.stopWork = true;
0938: try {
0939: t1.join();
0940: } catch (InterruptedException e) {
0941: fail(INTERRUPTED_MESSAGE);
0942: }
0943: long tIdTerm = t1.getId();
0944: assertEquals("Thread ID after termination should not change",
0945: tIdRun, tIdTerm);
0946: }
0947:
0948: /**
0949: * Verify the getName() method for a thread created with the default name.
0950: * It should start with "Thread-".
0951: */
0952: public void testGetNameDefault() {
0953: Thread t = new Thread();
0954: String name = t.getName();
0955: assertEquals("Thread name must start with 'Thread-'", 0, name
0956: .indexOf("Thread-"));
0957: }
0958:
0959: /**
0960: * Verify the getName() method for a thread created with the given name.
0961: */
0962: public void testGetName() {
0963: Thread t = new Thread("newThread");
0964: String name = t.getName();
0965: assertEquals("newThread", name);
0966: }
0967:
0968: /**
0969: * Verify the getPriority() method for a newly created thread.
0970: */
0971: public void testGetPriority() {
0972: Thread t = new Thread();
0973: int p = t.getPriority();
0974: assertTrue("The thread's priority is out of range",
0975: Thread.MIN_PRIORITY <= p && p <= Thread.MAX_PRIORITY);
0976: }
0977:
0978: /**
0979: * Get the stack trace of a thread.
0980: * Should be empty for new and terminated threads.
0981: * Should not be empty for running threads.
0982: */
0983: public void testGetStackTrace() {
0984: ThreadRunning tR = new ThreadRunning();
0985:
0986: // get stack trace of a new thread
0987: StackTraceElement ste[] = tR.getStackTrace();
0988: assertEquals("stack dump of a new thread is not empty",
0989: ste.length, 0);
0990: tR.start();
0991:
0992: // get stack trace of a running thread
0993: waitTime = waitDuration;
0994: do {
0995: ste = tR.getStackTrace();
0996: } while (ste.length == 0 && !(expired = doSleep(10)));
0997: if (expired) {
0998: fail("stack dump of a running thread is empty");
0999: } else {
1000: assertTrue("incorrect length", ste.length >= 1);
1001: /*
1002: // commented: sometimes it returns Thread.runImpl
1003: assertEquals("incorrect class name",
1004: "java.lang.ThreadTest$ThreadRunning",
1005: ste[0].getClassName());
1006: assertEquals("incorrect method name",
1007: "run", ste[0].getMethodName());
1008: */
1009: }
1010:
1011: // get stack trace of a terminated thread
1012: tR.stopWork = true;
1013: try {
1014: tR.join();
1015: } catch (InterruptedException e) {
1016: fail(INTERRUPTED_MESSAGE);
1017: }
1018: waitTime = waitDuration;
1019: do {
1020: ste = tR.getStackTrace();
1021: } while (ste.length != 0 && !(expired = doSleep(10)));
1022: if (expired) {
1023: fail("stack dump of a terminated thread is not empty");
1024: }
1025: }
1026:
1027: /**
1028: * Verify getAllStackTraces()
1029: */
1030: public void testGetAllStackTraces() {
1031: StackTraceElement ste[] = null;
1032: ThreadRunning tR = new ThreadRunning("MyThread");
1033: tR.start();
1034:
1035: Map<Thread, StackTraceElement[]> m = Thread.getAllStackTraces();
1036: tR.stopWork = true;
1037: assertTrue("getAllStackTraces() returned an empty Map", m
1038: .size() > 0);
1039:
1040: // verify stack traces of all threads
1041: Set<Thread> threadSet = m.keySet();
1042: for (Thread t : threadSet) {
1043: ste = m.get(t);
1044: assertNotNull("improper stack trace for thread " + t, ste);
1045: }
1046: }
1047:
1048: /**
1049: * Get the thread group of a thread created in the current thread's
1050: * thread group.
1051: */
1052: public void testGetThreadGroup() {
1053: Thread t = new Thread();
1054: ThreadGroup threadGroup = t.getThreadGroup();
1055: ThreadGroup curThreadGroup = Thread.currentThread()
1056: .getThreadGroup();
1057: assertEquals("incorrect value returned by getThreadGroup()",
1058: curThreadGroup, threadGroup);
1059: }
1060:
1061: /**
1062: * Get the thread group of a thread created in the specified thread group.
1063: */
1064: public void testGetThreadGroup1() {
1065: ThreadGroup tg = new ThreadGroup("group1");
1066: Thread t = new Thread(tg, "t1");
1067: ThreadGroup threadGroup = t.getThreadGroup();
1068: assertEquals("incorrect value returned by getThreadGroup()",
1069: tg, threadGroup);
1070: }
1071:
1072: /**
1073: * Get the thread group of a dead thread.
1074: */
1075: public void testGetThreadGroup_DeadThread() {
1076: ThreadRunning t = new ThreadRunning();
1077: t.start();
1078: t.stopWork = true;
1079: try {
1080: t.join();
1081: } catch (InterruptedException e) {
1082: fail(INTERRUPTED_MESSAGE);
1083: }
1084: assertNull("Thread group of a dead thread must be null", t
1085: .getThreadGroup());
1086: }
1087:
1088: /**
1089: * Get the state of a blocked thread.
1090: */
1091: public void testGetStateBlocked() {
1092: Team team = new Team();
1093: RunProject pr1 = new RunProject(team);
1094: pr1.start();
1095: waitTime = waitDuration;
1096: while (team.i == 0 && !(expired = doSleep(10))) {
1097: }
1098: if (expired) {
1099: fail("pr1 has not been started");
1100: }
1101: RunProject pr2 = new RunProject(team);
1102: pr2.start();
1103: Thread.State state;
1104: waitTime = waitDuration;
1105: do {
1106: state = pr2.getState();
1107: } while (!state.equals(Thread.State.BLOCKED)
1108: && !(expired = doSleep(10)));
1109: team.stopWork();
1110: if (expired) {
1111: fail("BLOCKED state has not been set");
1112: }
1113: }
1114:
1115: /**
1116: * Get the state of a new thread.
1117: */
1118: public void testGetStateNew() {
1119: ThreadRunning tR = new ThreadRunning();
1120: Thread.State state = tR.getState();
1121: assertEquals(Thread.State.NEW, state);
1122: }
1123:
1124: /**
1125: * Get the state of a new thread.
1126: */
1127: public void testGetStateNew1() {
1128: Square s = new Square(15);
1129: Thread t = new Thread(s);
1130: assertEquals(Thread.State.NEW, t.getState());
1131: }
1132:
1133: /**
1134: * Get the state of a runnable thread.
1135: */
1136: public void testGetStateRunnable() {
1137: ThreadRunning tR = new ThreadRunning();
1138: tR.start();
1139: Thread.State state;
1140: waitTime = waitDuration;
1141: do {
1142: state = tR.getState();
1143: } while (!state.equals(Thread.State.RUNNABLE)
1144: && !(expired = doSleep(10)));
1145: tR.stopWork = true;
1146: if (expired) {
1147: fail("RUNNABLE state has not been set");
1148: }
1149: }
1150:
1151: /**
1152: * Get the state of a runnable thread.
1153: */
1154: public void testGetStateRunnable1() {
1155: Square s = new Square(15);
1156: Thread t = new Thread(s);
1157: t.start();
1158: Thread.State state;
1159: waitTime = waitDuration;
1160: do {
1161: state = t.getState();
1162: } while (!state.equals(Thread.State.RUNNABLE)
1163: && !(expired = doSleep(10)));
1164: s.stop = true;
1165: if (expired) {
1166: fail("RUNNABLE state has not been set");
1167: }
1168: }
1169:
1170: /**
1171: * Get the state of a terminated thread.
1172: */
1173: public void testGetStateTerminated() {
1174: ThreadRunning tR = new ThreadRunning();
1175: tR.start();
1176: tR.stopWork = true;
1177: try {
1178: tR.join();
1179: } catch (InterruptedException e) {
1180: fail(INTERRUPTED_MESSAGE);
1181: }
1182: Thread.State state;
1183: waitTime = waitDuration;
1184: do {
1185: state = tR.getState();
1186: } while (!state.equals(Thread.State.TERMINATED)
1187: && !(expired = doSleep(10)));
1188: if (expired) {
1189: fail("TERMINATED state has not been set");
1190: }
1191: }
1192:
1193: /**
1194: * Get the state of a terminated thread.
1195: */
1196: public void testGetStateTerminated1() {
1197: Square s = new Square(15);
1198: Thread tR = new Thread(s);
1199: tR.start();
1200: s.stop = true;
1201: try {
1202: tR.join();
1203: } catch (InterruptedException e) {
1204: fail(INTERRUPTED_MESSAGE);
1205: }
1206: Thread.State state = tR.getState();
1207: waitTime = waitDuration;
1208: while (!state.equals(Thread.State.TERMINATED)
1209: && !(expired = doSleep(10))) {
1210: state = tR.getState();
1211: }
1212: if (expired) {
1213: fail("TERMINATED state has not been set");
1214: }
1215: }
1216:
1217: /**
1218: * Get the state of a timed waiting thread.
1219: */
1220: public void testGetStateTimedWaiting() {
1221: Object lock = new Object();
1222: ThreadWaiting tW = new ThreadWaiting(Action.WAIT, 6000, 0, lock);
1223: try {
1224: synchronized (lock) {
1225: tW.start();
1226: while (!tW.started) {
1227: lock.wait();
1228: }
1229: }
1230: } catch (InterruptedException e) {
1231: fail(INTERRUPTED_MESSAGE);
1232: }
1233: Thread.State state;
1234: waitTime = waitDuration;
1235: do {
1236: state = tW.getState();
1237: } while (!state.equals(Thread.State.TIMED_WAITING)
1238: && !(expired = doSleep(10)));
1239: synchronized (tW) {
1240: tW.notify();
1241: }
1242: if (expired) {
1243: fail("TIMED_WAITING state has not been set");
1244: }
1245: }
1246:
1247: /**
1248: * Get the state of a waiting thread.
1249: */
1250: public void testGetStateWaiting() {
1251: Object lock = new Object();
1252: ThreadWaiting tW = new ThreadWaiting(Action.WAIT, 0, 0, lock);
1253: try {
1254: synchronized (lock) {
1255: tW.start();
1256: while (!tW.started) {
1257: lock.wait();
1258: }
1259: }
1260: } catch (InterruptedException e) {
1261: fail(INTERRUPTED_MESSAGE);
1262: }
1263: Thread.State state;
1264: waitTime = waitDuration;
1265: do {
1266: state = tW.getState();
1267: } while (!state.equals(Thread.State.WAITING)
1268: && !(expired = doSleep(10)));
1269: synchronized (tW) {
1270: tW.notify();
1271: }
1272: if (expired) {
1273: fail("WAITING state has not been set");
1274: }
1275: }
1276:
1277: class ExceptionHandler implements Thread.UncaughtExceptionHandler {
1278:
1279: public boolean wasCalled = false;
1280:
1281: public void uncaughtException(Thread t, Throwable e) {
1282: wasCalled = true;
1283: }
1284: }
1285:
1286: /**
1287: * Test for getUncaughtExceptionHandler()
1288: */
1289: public void testGetUncaughtExceptionHandler() {
1290: ThreadGroup tg = new ThreadGroup("test thread group");
1291: Thread t = new Thread(tg, "test thread");
1292: Thread.UncaughtExceptionHandler hndlr = t
1293: .getUncaughtExceptionHandler();
1294: assertSame("Thread's thread group is expected to be a handler",
1295: tg, hndlr);
1296: }
1297:
1298: /**
1299: * Test getUncaughtExceptionHandler() for a terminated thread
1300: */
1301: public void testGetUncaughtExceptionHandler_Null() {
1302: ThreadGroup tg = new ThreadGroup("test thread group");
1303: Thread t = new Thread(tg, "test thread");
1304: t.start();
1305: try {
1306: t.join();
1307: } catch (InterruptedException e) {
1308: fail(INTERRUPTED_MESSAGE);
1309: }
1310: Thread.State state;
1311: waitTime = waitDuration;
1312: do {
1313: state = t.getState();
1314: } while (!state.equals(Thread.State.TERMINATED)
1315: && !(expired = doSleep(10)));
1316: if (expired) {
1317: fail("TERMINATED state has not been set");
1318: }
1319: assertNull("handler should be null for a terminated thread", t
1320: .getUncaughtExceptionHandler());
1321: }
1322:
1323: /**
1324: * Test for setUncaughtExceptionHandler()
1325: */
1326: public void testSetUncaughtExceptionHandler() {
1327: ThreadGroup tg = new ThreadGroup("test thread group");
1328: Thread t = new Thread(tg, "test thread");
1329: ExceptionHandler eh = new ExceptionHandler();
1330: t.setUncaughtExceptionHandler(eh);
1331: assertSame("the handler has not been set", eh, t
1332: .getUncaughtExceptionHandler());
1333: }
1334:
1335: /**
1336: * Test for setUncaughtExceptionHandler(null)
1337: */
1338: public void testSetUncaughtExceptionHandler_Null() {
1339: ThreadGroup tg = new ThreadGroup("test thread group");
1340: Thread t = new Thread(tg, "test thread");
1341: t.setUncaughtExceptionHandler(null);
1342: assertSame("Thread's thread group is expected to be a handler",
1343: tg, t.getUncaughtExceptionHandler());
1344: }
1345:
1346: /**
1347: * Test set/get DefaultUncaughtExceptionHandler()
1348: */
1349: public void testSetDefaultUncaughtExceptionHandler() {
1350: ExceptionHandler eh = new ExceptionHandler();
1351: Thread.setDefaultUncaughtExceptionHandler(eh);
1352: assertSame("the default handler has not been set", eh, Thread
1353: .getDefaultUncaughtExceptionHandler());
1354: }
1355:
1356: /**
1357: * Test set/get DefaultUncaughtExceptionHandler(null)
1358: */
1359: public void testSetDefaultUncaughtExceptionHandler_Null() {
1360: Thread.setDefaultUncaughtExceptionHandler(null);
1361: assertNull("default handler should be null", Thread
1362: .getDefaultUncaughtExceptionHandler());
1363: }
1364:
1365: /**
1366: * Interrupt a newly created thread
1367: */
1368: public void testInterrupt_New() {
1369: Thread t = new Thread();
1370: t.interrupt();
1371: waitTime = waitDuration;
1372: while (!t.isInterrupted() && !(expired = doSleep(10))) {
1373: }
1374: if (expired) {
1375: fail("interrupt status has not changed to true");
1376: }
1377: }
1378:
1379: /**
1380: * Interrupt a running thread
1381: */
1382: public void testInterrupt_RunningThread() {
1383: ThreadRunning t = new ThreadRunning();
1384: t.start();
1385: waitTime = waitDuration;
1386: while (t.i == 0 && !(expired = doSleep(10))) {
1387: }
1388: if (expired) {
1389: fail("unexpected: thread's run() method has not started");
1390: }
1391: t.interrupt();
1392: waitTime = waitDuration;
1393: while (!t.isInterrupted() && !(expired = doSleep(10))) {
1394: }
1395: t.stopWork = true;
1396: if (expired) {
1397: fail("interrupt status has not changed to true");
1398: }
1399: }
1400:
1401: /**
1402: * Interrupt the current thread
1403: */
1404: public void testInterrupt_CurrentThread() {
1405: Thread t = new Thread() {
1406: public void run() {
1407: interrupt();
1408: }
1409: };
1410: t.start();
1411: waitTime = waitDuration;
1412: while (!t.isInterrupted() && !(expired = doSleep(10))) {
1413: }
1414: if (expired) {
1415: fail("interrupt status has not changed to true");
1416: }
1417: }
1418:
1419: /**
1420: * Interrupt a terminated thread
1421: */
1422: public void testInterrupt_Terminated() {
1423: ThreadRunning t = new ThreadRunning();
1424: t.start();
1425: waitTime = waitDuration;
1426: while (t.i == 0 && !(expired = doSleep(10))) {
1427: }
1428: if (expired) {
1429: fail("thread' run() method has not started");
1430: }
1431: t.stopWork = true;
1432: try {
1433: t.join();
1434: } catch (InterruptedException e) {
1435: fail(INTERRUPTED_MESSAGE);
1436: }
1437: t.interrupt();
1438: assertTrue("interrupt status has not changed to true", t
1439: .isInterrupted());
1440: }
1441:
1442: /**
1443: * Interrupt a joining thread
1444: */
1445: public void testInterrupt_Joining() {
1446: Object lock = new Object();
1447: ThreadWaiting t = new ThreadWaiting(Action.JOIN, 10000, 0, lock);
1448: try {
1449: synchronized (lock) {
1450: t.start();
1451: while (!t.started) {
1452: lock.wait();
1453: }
1454: }
1455: } catch (InterruptedException e) {
1456: fail(INTERRUPTED_MESSAGE);
1457: }
1458: t.interrupt();
1459: waitTime = waitDuration;
1460: while (!t.exceptionReceived && !(expired = doSleep(10))) {
1461: }
1462: if (expired) {
1463: fail("joining thread has not received the InterruptedException");
1464: }
1465: assertFalse("interrupt status has not been cleared", t
1466: .isInterrupted());
1467: }
1468:
1469: /**
1470: * Interrupt a sleeping thread
1471: */
1472: public void testInterrupt_Sleeping() {
1473: Object lock = new Object();
1474: ThreadWaiting t = new ThreadWaiting(Action.SLEEP, 10000, 0,
1475: lock);
1476: try {
1477: synchronized (lock) {
1478: t.start();
1479: while (!t.started) {
1480: lock.wait();
1481: }
1482: }
1483: } catch (InterruptedException e) {
1484: fail(INTERRUPTED_MESSAGE);
1485: }
1486: waitTime = waitDuration;
1487: while (!t.isAlive() && !(expired = doSleep(10))) {
1488: }
1489: if (expired) {
1490: fail("thread has not started for " + waitDuration + "ms");
1491: }
1492: t.interrupt();
1493: waitTime = waitDuration;
1494: while (!t.exceptionReceived && !(expired = doSleep(10))) {
1495: }
1496: if (expired) {
1497: fail("sleeping thread has not received the InterruptedException");
1498: }
1499: assertFalse("interrupt status has not been cleared", t
1500: .isInterrupted());
1501: }
1502:
1503: /**
1504: * Interrupt a waiting thread
1505: */
1506: public void testInterrupt_Waiting() {
1507: Object lock = new Object();
1508: ThreadWaiting t = new ThreadWaiting(Action.WAIT, 10000, 0, lock);
1509: try {
1510: synchronized (lock) {
1511: t.start();
1512: while (!t.started) {
1513: lock.wait();
1514: }
1515: }
1516: } catch (InterruptedException e) {
1517: fail(INTERRUPTED_MESSAGE);
1518: }
1519: waitTime = waitDuration;
1520: Thread.State ts = t.getState();
1521: while (ts != Thread.State.TIMED_WAITING
1522: && !(expired = doSleep(10))) {
1523: ts = t.getState();
1524: }
1525: if (expired) {
1526: fail("TIMED_WAITING state has not been reached");
1527: }
1528: t.interrupt();
1529: waitTime = waitDuration;
1530: while (!t.exceptionReceived && !(expired = doSleep(10))) {
1531: }
1532: if (expired) {
1533: fail("waiting thread has not received the InterruptedException");
1534: }
1535: assertFalse("interrupt status has not been cleared", t
1536: .isInterrupted());
1537: }
1538:
1539: static final int COUNT = 100;
1540: volatile int base;
1541:
1542: /**
1543: * Check that interrupt and notify happen exactly once for each
1544: * <code>notify()</code> and <code>interrupt()</code> call.
1545: */
1546: public void testInterrupt_Staging() {
1547: ThreadStaging t = new ThreadStaging();
1548:
1549: base = 0;
1550: t.start();
1551:
1552: try {
1553: for (base = 0; base < COUNT;) {
1554: synchronized (t) {
1555: t.waitStage("notify");
1556: t.notify();
1557:
1558: t.waitStage("interrupt");
1559: t.interrupt();
1560: }
1561: }
1562: } catch (InterruptedException e) {
1563: fail("Unexpected exception: " + e);
1564: }
1565: }
1566:
1567: private class ThreadStaging extends Thread {
1568: static final long TIMEOUT = 100;
1569: int stage;
1570:
1571: public void run() {
1572: for (stage = 0; stage < COUNT;) {
1573:
1574: try {
1575: waitBase();
1576: } catch (InterruptedException e) {
1577: fail("Unexpected exception: " + e);
1578: }
1579: assertEquals(
1580: "Stages are not synchronized after interrupt",
1581: stage, base);
1582:
1583: try {
1584: waitBase();
1585: fail("The thread should be interrupted");
1586: } catch (InterruptedException e) {
1587: assertEquals(
1588: "Stages are not synchronized after interrupt",
1589: stage, base);
1590: continue;
1591: }
1592: fail("The thread should be interrupted by (InterruptedException");
1593: }
1594: }
1595:
1596: public synchronized void waitStage(String stageName)
1597: throws InterruptedException {
1598: for (int i = 0; (base == stage) && (i < COUNT); i++) {
1599: wait(TIMEOUT);
1600: }
1601: assertEquals("waitFor " + stageName
1602: + ": stages are not synchronized before", stage,
1603: ++base);
1604: }
1605:
1606: synchronized void waitBase() throws InterruptedException {
1607: stage++;
1608: notify();
1609: wait(TIMEOUT);
1610: }
1611: }
1612:
1613: /**
1614: * Verify that the current thread is alive
1615: */
1616: public void testIsAliveCurrent() {
1617: assertTrue("The current thread must be alive!", Thread
1618: .currentThread().isAlive());
1619: }
1620:
1621: /**
1622: * Verify that a thread is alive just after start
1623: */
1624: public void testIsAlive() {
1625: ThreadRunning t = new ThreadRunning();
1626: t.start();
1627: assertTrue("The started thread must be alive!", t.isAlive());
1628: t.stopWork = true;
1629: }
1630:
1631: /**
1632: * Verify the isAlive() method for a newly created, running
1633: * and finished thread
1634: */
1635: public void testIsAlive1() {
1636: TestThread t = new TestThread();
1637: assertFalse(
1638: "Newly created and not started thread must not be alive!",
1639: t.isAlive());
1640: try {
1641: synchronized (t) {
1642: t.start();
1643: t.wait();
1644: }
1645: if (!t.isAlive()) {
1646: if (t.e != null) {
1647: fail("The thread was interrupted");
1648: }
1649: fail("The thread must be alive");
1650: }
1651: synchronized (t) {
1652: t.notify();
1653: }
1654: waitTime = waitDuration;
1655: while (t.isAlive() && !(expired = doSleep(10))) {
1656: t.join();
1657: }
1658: if (expired) {
1659: fail("thread has not finished for " + waitDuration
1660: + "ms");
1661: }
1662: } catch (InterruptedException e) {
1663: fail("Current thread was interrupted");
1664: }
1665: }
1666:
1667: /**
1668: * Verify the isAlive() method for a few threads
1669: */
1670: public void testIsAlive2() {
1671: ThreadRunning t1 = new ThreadRunning();
1672: ThreadRunning t2 = new ThreadRunning();
1673: ThreadRunning t3 = new ThreadRunning();
1674: assertFalse("t1 has not started and must not be alive", t1
1675: .isAlive());
1676: assertFalse("t2 has not started and must not be alive", t2
1677: .isAlive());
1678: assertFalse("t3 has not started and must not be alive", t3
1679: .isAlive());
1680: t1.start();
1681: t2.start();
1682: t3.start();
1683: assertTrue("t1 must be alive", t1.isAlive());
1684: assertTrue("t2 must be alive", t2.isAlive());
1685: assertTrue("t3 must be alive", t3.isAlive());
1686: t1.stopWork = true;
1687: t2.stopWork = true;
1688: t3.stopWork = true;
1689: try {
1690: t1.join();
1691: t2.join();
1692: t3.join();
1693: } catch (InterruptedException e) {
1694: fail("threads have been interrupted");
1695: }
1696: assertFalse("t1 has finished and must not be alive", t1
1697: .isAlive());
1698: assertFalse("t2 has finished and must not be alive", t2
1699: .isAlive());
1700: assertFalse("t3 has finished and must not be alive", t3
1701: .isAlive());
1702: }
1703:
1704: public void testIsDaemonFalse() {
1705: Thread t = new Thread();
1706: assertFalse("thread should not be daemon", t.isDaemon());
1707: }
1708:
1709: public void testIsDaemonTrue() {
1710: Thread t = new Thread();
1711: t.setDaemon(true);
1712: assertTrue("thread should be daemon", t.isDaemon());
1713: }
1714:
1715: /**
1716: * Check that interrupt status is not affected by isInterrupted()
1717: */
1718: public void testIsInterrupted() {
1719: ThreadRunning t = new ThreadRunning();
1720: t.start();
1721: waitTime = waitDuration;
1722: while (t.i == 0 && !(expired = doSleep(10))) {
1723: }
1724: if (expired) {
1725: fail("unexpected: thread's run() method has not started");
1726: }
1727: t.interrupt();
1728: waitTime = waitDuration;
1729: while (!t.isInterrupted() && !(expired = doSleep(10))) {
1730: }
1731: t.stopWork = true;
1732: if (expired) {
1733: fail("interrupt status has not changed to true");
1734: }
1735: assertTrue(
1736: "interrupt status has been cleared by the previous call",
1737: t.isInterrupted());
1738: }
1739:
1740: /**
1741: * Test for void join(long)
1742: */
1743: public void testJoinlong() {
1744: long millis = 2000;
1745: ThreadRunning t = new ThreadRunning();
1746: t.start();
1747: long joinStartTime = 0;
1748: long curTime = 0;
1749: try {
1750: joinStartTime = System.currentTimeMillis();
1751: t.join(millis);
1752: curTime = System.currentTimeMillis();
1753: } catch (InterruptedException e) {
1754: fail(INTERRUPTED_MESSAGE);
1755: }
1756: long duration = curTime - joinStartTime;
1757: // we allow the test to wait 2.5% less
1758: long atLeast = (millis - 50);
1759: t.stopWork = true;
1760: assertTrue("join should wait for at least " + atLeast
1761: + " but waited for " + duration, duration >= atLeast);
1762: }
1763:
1764: /**
1765: * Test for void join(long, int)
1766: */
1767: public void testJoinlongint() {
1768: long millis = 2000;
1769: int nanos = 999999;
1770: ThreadRunning t = new ThreadRunning();
1771: t.start();
1772: long joinStartTime = 0;
1773: long curTime = 0;
1774: try {
1775: joinStartTime = System.currentTimeMillis();
1776: t.join(millis, nanos);
1777: curTime = System.currentTimeMillis();
1778: } catch (InterruptedException e) {
1779: fail(INTERRUPTED_MESSAGE);
1780: }
1781: long duration = 1000000 * (curTime - joinStartTime);
1782: // we allow the test to wait 2.5% less
1783: long atLeast = (millis - 50) * 1000000 + nanos;
1784: t.stopWork = true;
1785: assertTrue("join should wait for at least " + atLeast
1786: + " but waited for " + duration, duration >= atLeast);
1787: }
1788:
1789: /**
1790: * Test for run(). Should do nothing.
1791: */
1792: public void testRun() {
1793: Thread t = new Thread();
1794: Thread.State tsBefore = t.getState();
1795: t.run();
1796: Thread.State tsAfter = t.getState();
1797: assertEquals("run() should do nothing", tsBefore, tsAfter);
1798: }
1799:
1800: /**
1801: * Test for run(). Should call run() of a Runnable object.
1802: */
1803: public void testRun_Runnable() {
1804: Square s = new Square(25, true);
1805: Thread t = new Thread(s);
1806: t.run();
1807: assertEquals("thread has not run", 625, s.squaredNumber);
1808: }
1809:
1810: public void testSetContextClassLoader() {
1811: Class c = null;
1812: try {
1813: c = Class.forName("java.lang.String");
1814: } catch (ClassNotFoundException e) {
1815: fail("ClassNotFoundException for java.lang.String");
1816: }
1817: ClassLoader cl = c.getClassLoader();
1818: ThreadRunningAnotherThread t = new ThreadRunningAnotherThread();
1819: ClassLoader clt = t.getContextClassLoader();
1820: t.setContextClassLoader(cl);
1821: ClassLoader clNew = t.getContextClassLoader();
1822: assertSame("incorrect ClassLoader has been set", cl, clNew);
1823: assertNotSame("ClassLoader has not changed", clt, clNew);
1824: }
1825:
1826: /**
1827: * Make a thread daemon
1828: */
1829: public void testSetDaemon() {
1830: Thread t = new Thread();
1831: assertFalse(
1832: "Assert 0: the newly created thread must not be daemon",
1833: t.isDaemon());
1834: t.setDaemon(true);
1835: assertTrue("Assert 1: the thread must be daemon", t.isDaemon());
1836: }
1837:
1838: /**
1839: * Try to make a running thread daemon
1840: */
1841: public void testSetDaemonLiveThread() {
1842: ThreadRunning t = new ThreadRunning();
1843: t.start();
1844: try {
1845: t.setDaemon(true);
1846: t.stopWork = true;
1847: try {
1848: t.join();
1849: } catch (InterruptedException e) {
1850: fail(INTERRUPTED_MESSAGE);
1851: }
1852: fail("IllegalThreadStateException has not been thrown");
1853: } catch (IllegalThreadStateException e) {
1854: return;
1855: }
1856: }
1857:
1858: /**
1859: * Make a dead thread daemon
1860: */
1861: public void testSetDaemonDeadThread() {
1862: ThreadRunning t = new ThreadRunning();
1863: t.start();
1864: t.stopWork = true;
1865: try {
1866: t.join();
1867: } catch (InterruptedException e) {
1868: fail(INTERRUPTED_MESSAGE);
1869: }
1870: boolean threadDaemonStatus = t.isDaemon();
1871: try {
1872: t.setDaemon(!threadDaemonStatus);
1873: } catch (IllegalThreadStateException e) {
1874: fail("IllegalThreadStateException should not be thrown"
1875: + " for a dead thread");
1876: }
1877: }
1878:
1879: /**
1880: * Verify the setName() method
1881: */
1882: public void testSetName() {
1883: Thread thread = new Thread();
1884: String newName = "qwerty";
1885: thread.setName(newName);
1886: assertEquals("setName() has not set the new name", newName,
1887: thread.getName());
1888: }
1889:
1890: /**
1891: * Verify the setName(null) method
1892: */
1893: public void testSetNameNull() {
1894: Thread thread = new Thread();
1895: try {
1896: thread.setName(null);
1897: } catch (NullPointerException e) {
1898: return;
1899: }
1900: fail("setName() should not accept null names");
1901: }
1902:
1903: /**
1904: * Verify the setName() method when a SecurityManager is set.
1905: */
1906: public void testSetName_CheckAccess() {
1907: sm = System.getSecurityManager();
1908: System.setSecurityManager(new ReversibleSecurityManager());
1909: Thread thread = new Thread();
1910: String newName = "qwerty";
1911: thread.setName(newName);
1912: String gotName = thread.getName();
1913: System.setSecurityManager(sm);
1914: assertEquals("setName() has not set the new name", newName,
1915: gotName);
1916: }
1917:
1918: /**
1919: * Verify the setPriority() method to a dead thread.
1920: * NullPointerException is expected
1921: */
1922: public void testSetPriorityDeadThread() {
1923: ThreadGroup tg = new ThreadGroup("group1");
1924: int maxTGPriority = Thread.MAX_PRIORITY - 1;
1925: tg.setMaxPriority(maxTGPriority);
1926: ThreadRunning t = new ThreadRunning(tg, "running");
1927: t.start();
1928: t.stopWork = true;
1929: try {
1930: t.join();
1931: } catch (InterruptedException e) {
1932: fail(INTERRUPTED_MESSAGE);
1933: }
1934: int newPriority = Thread.MAX_PRIORITY;
1935: try {
1936: t.setPriority(newPriority);
1937: fail("NullPointerException has not been thrown");
1938: } catch (NullPointerException e) {
1939: return;
1940: }
1941: }
1942:
1943: /**
1944: * Verify the setPriority() method with new priority higher
1945: * than the maximum permitted priority for the thread's group.
1946: */
1947: public void testSetPriorityGreaterMax() {
1948: ThreadGroup tg = new ThreadGroup("group1");
1949: int maxTGPriority = Thread.MAX_PRIORITY - 1;
1950: tg.setMaxPriority(maxTGPriority);
1951: Thread t = new Thread(tg, "t");
1952: t.setPriority(Thread.MAX_PRIORITY);
1953: assertEquals(maxTGPriority, t.getPriority());
1954: }
1955:
1956: /**
1957: * Verify the setPriority() method with new priority lower
1958: * than the current one.
1959: */
1960: public void testSetPriorityLower() {
1961: Thread t = new Thread();
1962: int p = t.getPriority();
1963: int newPriority = p - 1;
1964: if (newPriority >= Thread.MIN_PRIORITY) {
1965: t.setPriority(newPriority);
1966: assertEquals(newPriority, t.getPriority());
1967: }
1968: }
1969:
1970: /**
1971: * Verify the setPriority() method with new priority out of the legal range.
1972: */
1973: public void testSetPriorityOutOfRange() {
1974: Thread t = new Thread();
1975: try {
1976: t.setPriority(Thread.MAX_PRIORITY + 2);
1977: fail("IllegalArgumentException should be thrown when setting "
1978: + "illegal priority");
1979: } catch (IllegalArgumentException e) {
1980: return;
1981: }
1982: }
1983:
1984: /**
1985: * Verify the setPriority() method when a SecurityManager is set.
1986: */
1987: public void testSetPriority_CheckAccess() {
1988: sm = System.getSecurityManager();
1989: System.setSecurityManager(new ReversibleSecurityManager());
1990: Thread t = new Thread();
1991: int p = t.getPriority();
1992: t.setPriority(p);
1993: int newP = t.getPriority();
1994: System.setSecurityManager(sm);
1995: assertEquals(p, newP);
1996: }
1997:
1998: /**
1999: * Start the already started thread
2000: */
2001: public void testStart_Started() {
2002: ThreadRunning t = new ThreadRunning();
2003: t.start();
2004: try {
2005: t.start();
2006: t.stopWork = true;
2007: fail("IllegalThreadStateException is expected when starting "
2008: + "a started thread");
2009: } catch (IllegalThreadStateException e) {
2010: t.stopWork = true;
2011: }
2012: }
2013:
2014: /**
2015: * Start the already finished thread
2016: */
2017: public void testStart_Finished() {
2018: ThreadRunning t = new ThreadRunning();
2019: t.start();
2020: t.stopWork = true;
2021: try {
2022: t.join();
2023: } catch (InterruptedException e) {
2024: fail(INTERRUPTED_MESSAGE);
2025: }
2026: try {
2027: t.start();
2028: fail("IllegalThreadStateException is expected when starting "
2029: + "a finished thread");
2030: } catch (IllegalThreadStateException e) {
2031: return;
2032: }
2033: }
2034: }
|