1 4 package com.tc.util.concurrent; 5 6 import EDU.oswego.cs.dl.util.concurrent.SynchronizedBoolean; 7 8 import java.util.Random ; 9 10 import junit.framework.TestCase; 11 12 17 public class SetOnceFlagTest extends TestCase { 18 19 public void testRace() throws InterruptedException { 20 final Random random = new Random (); 21 22 for (int i = 0; i < 50; i++) { 23 final SetOnceFlag flag = new SetOnceFlag(); 24 final SynchronizedBoolean thread1 = new SynchronizedBoolean(false); 25 final SynchronizedBoolean thread2 = new SynchronizedBoolean(false); 26 27 Runnable r1 = new Runnable () { 28 public void run() { 29 try { 30 Thread.sleep(random.nextInt(50)); 31 } catch (InterruptedException e) { 32 fail(); 33 } 34 35 try { 36 flag.set(); 37 thread1.set(true); } catch (IllegalStateException iae) { 39 } 41 } 42 }; 43 44 Runnable r2 = new Runnable () { 45 public void run() { 46 try { 47 try { 48 Thread.sleep(random.nextInt(50)); 49 } catch (InterruptedException e) { 50 fail(); 51 } 52 53 flag.set(); 54 thread2.set(true); } catch (IllegalStateException iae) { 56 } 58 } 59 }; 60 61 Thread t1 = new Thread (r1); 62 Thread t2 = new Thread (r2); 63 t1.start(); 64 t2.start(); 65 t1.join(); 66 t2.join(); 67 68 System.out.println("The winner is thread " + (thread1.get() ? "1" : "2")); 69 70 assertTrue(thread1.get() ^ thread2.get()); 71 } 72 } 73 74 public void testAttemptSet() { 75 SetOnceFlag flag = new SetOnceFlag(); 76 77 flag.set(); 78 79 assertFalse(flag.attemptSet()); 80 } 81 82 public void testMultiSet() { 83 SetOnceFlag flag = new SetOnceFlag(); 84 85 flag.set(); 87 88 for (int i = 0; i < 100; i++) { 90 try { 91 flag.set(); 92 fail(); 93 } catch (IllegalStateException iae) { 94 } 96 } 97 } 98 99 public void testMultiRead() { 100 SetOnceFlag flag = new SetOnceFlag(); 101 102 flag.set(); 104 105 for (int i = 0; i < 100; i++) { 107 assertTrue(flag.isSet()); 108 } 109 } 110 111 public void testInitSet() { 112 SetOnceFlag flag = new SetOnceFlag(true); 113 114 try { 115 flag.set(); 116 fail(); 117 } catch (IllegalStateException iae) { 118 } 120 } 121 122 } 123 | Popular Tags |