1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
* Other contributors include Andrew Wright, Jeffrey Hayes, |
6 |
* Pat Fisher, Mike Judd. |
7 |
*/ |
8 |
|
9 |
import junit.framework.*; |
10 |
import java.util.concurrent.Semaphore; |
11 |
|
12 |
public class ThreadLocalTest extends JSR166TestCase { |
13 |
public static void main(String[] args) { |
14 |
junit.textui.TestRunner.run(suite()); |
15 |
} |
16 |
|
17 |
public static Test suite() { |
18 |
return new TestSuite(ThreadLocalTest.class); |
19 |
} |
20 |
|
21 |
static ThreadLocal<Integer> tl = new ThreadLocal<Integer>() { |
22 |
public Integer initialValue() { |
23 |
return one; |
24 |
} |
25 |
}; |
26 |
|
27 |
static InheritableThreadLocal<Integer> itl = |
28 |
new InheritableThreadLocal<Integer>() { |
29 |
protected Integer initialValue() { |
30 |
return zero; |
31 |
} |
32 |
|
33 |
protected Integer childValue(Integer parentValue) { |
34 |
return new Integer(parentValue.intValue() + 1); |
35 |
} |
36 |
}; |
37 |
|
38 |
/** |
39 |
* remove causes next access to return initial value |
40 |
*/ |
41 |
public void testRemove() { |
42 |
assertSame(tl.get(), one); |
43 |
tl.set(two); |
44 |
assertSame(tl.get(), two); |
45 |
tl.remove(); |
46 |
assertSame(tl.get(), one); |
47 |
} |
48 |
|
49 |
/** |
50 |
* remove in InheritableThreadLocal causes next access to return |
51 |
* initial value |
52 |
*/ |
53 |
public void testRemoveITL() { |
54 |
assertSame(itl.get(), zero); |
55 |
itl.set(two); |
56 |
assertSame(itl.get(), two); |
57 |
itl.remove(); |
58 |
assertSame(itl.get(), zero); |
59 |
} |
60 |
|
61 |
private class ITLThread extends Thread { |
62 |
final int[] x; |
63 |
ITLThread(int[] array) { x = array; } |
64 |
public void run() { |
65 |
Thread child = null; |
66 |
if (itl.get().intValue() < x.length - 1) { |
67 |
child = new ITLThread(x); |
68 |
child.start(); |
69 |
} |
70 |
Thread.yield(); |
71 |
|
72 |
int threadId = itl.get().intValue(); |
73 |
for (int j = 0; j < threadId; j++) { |
74 |
x[threadId]++; |
75 |
Thread.yield(); |
76 |
} |
77 |
|
78 |
if (child != null) { // Wait for child (if any) |
79 |
try { |
80 |
child.join(); |
81 |
} catch (InterruptedException e) { |
82 |
threadUnexpectedException(e); |
83 |
} |
84 |
} |
85 |
} |
86 |
} |
87 |
|
88 |
/** |
89 |
* InheritableThreadLocal propagates generic values. |
90 |
*/ |
91 |
public void testGenericITL() throws InterruptedException { |
92 |
final int threadCount = 10; |
93 |
final int x[] = new int[threadCount]; |
94 |
Thread progenitor = new ITLThread(x); |
95 |
progenitor.start(); |
96 |
progenitor.join(); |
97 |
for (int i = 0; i < threadCount; i++) { |
98 |
assertEquals(i, x[i]); |
99 |
} |
100 |
} |
101 |
} |