001: /*
002: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
003: */
004: package com.tc.util.concurrent;
005:
006: import EDU.oswego.cs.dl.util.concurrent.SynchronizedBoolean;
007:
008: import java.util.Random;
009:
010: import junit.framework.TestCase;
011:
012: /**
013: * Test cases for SetOnceFlag
014: *
015: * @author teck
016: */
017: public class SetOnceFlagTest extends TestCase {
018:
019: public void testRace() throws InterruptedException {
020: final Random random = new Random();
021:
022: for (int i = 0; i < 50; i++) {
023: final SetOnceFlag flag = new SetOnceFlag();
024: final SynchronizedBoolean thread1 = new SynchronizedBoolean(
025: false);
026: final SynchronizedBoolean thread2 = new SynchronizedBoolean(
027: false);
028:
029: Runnable r1 = new Runnable() {
030: public void run() {
031: try {
032: Thread.sleep(random.nextInt(50));
033: } catch (InterruptedException e) {
034: fail();
035: }
036:
037: try {
038: flag.set();
039: thread1.set(true); // I win!
040: } catch (IllegalStateException iae) {
041: // I didn't win ;-(
042: }
043: }
044: };
045:
046: Runnable r2 = new Runnable() {
047: public void run() {
048: try {
049: try {
050: Thread.sleep(random.nextInt(50));
051: } catch (InterruptedException e) {
052: fail();
053: }
054:
055: flag.set();
056: thread2.set(true); // I win!
057: } catch (IllegalStateException iae) {
058: // I didn't win ;-(
059: }
060: }
061: };
062:
063: Thread t1 = new Thread(r1);
064: Thread t2 = new Thread(r2);
065: t1.start();
066: t2.start();
067: t1.join();
068: t2.join();
069:
070: System.out.println("The winner is thread "
071: + (thread1.get() ? "1" : "2"));
072:
073: assertTrue(thread1.get() ^ thread2.get());
074: }
075: }
076:
077: public void testAttemptSet() {
078: SetOnceFlag flag = new SetOnceFlag();
079:
080: flag.set();
081:
082: assertFalse(flag.attemptSet());
083: }
084:
085: public void testMultiSet() {
086: SetOnceFlag flag = new SetOnceFlag();
087:
088: // set it once
089: flag.set();
090:
091: // try setting it many more times
092: for (int i = 0; i < 100; i++) {
093: try {
094: flag.set();
095: fail();
096: } catch (IllegalStateException iae) {
097: // expected
098: }
099: }
100: }
101:
102: public void testMultiRead() {
103: SetOnceFlag flag = new SetOnceFlag();
104:
105: // set it once
106: flag.set();
107:
108: // try reading it many times
109: for (int i = 0; i < 100; i++) {
110: assertTrue(flag.isSet());
111: }
112: }
113:
114: public void testInitSet() {
115: SetOnceFlag flag = new SetOnceFlag(true);
116:
117: try {
118: flag.set();
119: fail();
120: } catch (IllegalStateException iae) {
121: // expected
122: }
123: }
124:
125: }
|