KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > util > concurrent > SetOnceRefTest


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.util.concurrent;
5
6 import junit.framework.TestCase;
7
8 /**
9  * test cases for SetOnceRef
10  *
11  * @author teck
12  */

13 public class SetOnceRefTest extends TestCase {
14
15   public void testAllowsNull() {
16     SetOnceRef ref = new SetOnceRef(false);
17
18     assertFalse(ref.allowsNull());
19
20     try {
21       ref.set(null);
22       fail();
23     } catch (IllegalArgumentException JavaDoc iae) {
24       // expected
25
}
26
27     Object JavaDoc val = new Object JavaDoc();
28     ref.set(val);
29
30     assertTrue(ref.get() == val);
31   }
32
33   public void testSetNull() {
34     final SetOnceRef ref1 = new SetOnceRef(true);
35     ref1.set(null);
36     final SetOnceRef ref2 = new SetOnceRef(null, true);
37
38     assertTrue(ref1.get() == null);
39     assertTrue(ref2.get() == null);
40   }
41
42   public void testSetTwice() {
43     final Object JavaDoc val1 = new Object JavaDoc();
44     final Object JavaDoc val2 = new Object JavaDoc();
45
46     final SetOnceRef ref1 = new SetOnceRef();
47     ref1.set(val1);
48     final SetOnceRef ref2 = new SetOnceRef(val2);
49
50     assertTrue(ref1.get() == val1);
51     assertTrue(ref2.get() == val2);
52
53     try {
54       ref1.set(val1);
55       fail();
56     } catch (IllegalStateException JavaDoc e) {
57       // expected
58
}
59
60     try {
61       ref2.set(val2);
62       fail();
63     } catch (IllegalStateException JavaDoc e) {
64       // expected
65
}
66   }
67
68   public void testGetMany() {
69     final Object JavaDoc JUnitGetsMeHard = new Object JavaDoc();
70     final SetOnceRef ref = new SetOnceRef(JUnitGetsMeHard);
71
72     for (int i = 0; i < 1000; i++) {
73       assertTrue(ref.get() == JUnitGetsMeHard);
74     }
75   }
76
77   public void testThreadAccess() throws InterruptedException JavaDoc {
78     final Object JavaDoc val = new Object JavaDoc();
79
80     final SetOnceRef ref = new SetOnceRef();
81
82     Thread JavaDoc other = new Thread JavaDoc(new Runnable JavaDoc() {
83       public void run() {
84         ref.set(val);
85       }
86     });
87
88     other.start();
89     other.join();
90
91     assertTrue(ref.get() == val);
92   }
93
94 }
95
Popular Tags