1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package net.grinder.util.thread;
23
24 import java.util.TimerTask;
25
26 import net.grinder.common.UncheckedInterruptedException;
27 import net.grinder.testutility.Time;
28
29 import junit.framework.Assert;
30 import junit.framework.TestCase;
31
32
33
34
35
36
37
38 public class TestMonitor extends TestCase {
39
40 public void testWaitNoInterruptException() throws Exception {
41 final Condition monitor = new Condition();
42
43 final DoWait wait1 = new DoWait(monitor);
44
45 final Thread thread1 = new Thread(wait1);
46 thread1.start();
47 wait1.waitUntilWaiting(true);
48 synchronized (monitor) {
49 monitor.notify();
50 }
51 wait1.assertSuccess();
52 thread1.join();
53
54 final Thread thread2 = new Thread(wait1);
55 thread2.start();
56 wait1.waitUntilWaiting(true);
57 synchronized (monitor) {
58 thread2.interrupt();
59 }
60 wait1.assertException(UncheckedInterruptedException.class);
61 thread1.join();
62
63 final DoWait wait2 = new DoWait(monitor, 100);
64
65 final Thread thread3 = new Thread(wait2);
66 thread3.start();
67 wait2.waitUntilWaiting(true);
68 synchronized (monitor) {
69 monitor.notify();
70 }
71 wait2.assertSuccess();
72 thread3.join();
73
74 final Thread thread4 = new Thread(wait2);
75 thread4.start();
76 wait2.waitUntilWaiting(true);
77 synchronized (monitor) {
78 thread4.interrupt();
79 }
80 wait2.assertException(UncheckedInterruptedException.class);
81 thread4.join();
82
83 assertTrue(new Time(100, 200) {
84 public void doIt() throws Exception {
85 wait2.run();
86 }
87 }.run());
88 }
89
90 private static final class DoWait extends TimerTask {
91 private final Condition m_monitor;
92 private final long m_time;
93 private Throwable m_threw;
94 private boolean m_waiting;
95
96 public DoWait(Condition monitor) {
97 this(monitor, -1);
98 }
99
100 private DoWait(Condition monitor, long time) {
101 super();
102 m_monitor = monitor;
103 m_time = time;
104 }
105
106 public void waitUntilWaiting(boolean b) throws InterruptedException {
107 synchronized (m_monitor) {
108 while (m_waiting != b) {
109 m_monitor.wait();
110 }
111 }
112 }
113
114 public void run() {
115 m_threw = null;
116
117 synchronized (m_monitor) {
118 try {
119 m_waiting = true;
120 m_monitor.notifyAll();
121
122 if (m_time >= 0) {
123 m_monitor.waitNoInterrruptException(m_time);
124 }
125 else {
126 m_monitor.waitNoInterrruptException();
127 }
128 }
129 catch (Throwable t) {
130 m_threw = t;
131 }
132 finally {
133 m_waiting = false;
134 m_monitor.notifyAll();
135 }
136 }
137 }
138
139 public void assertSuccess() throws InterruptedException {
140 waitUntilWaiting(false);
141 Assert.assertNull(m_threw);
142 }
143
144 public void assertException(Class<?> c) throws InterruptedException {
145 waitUntilWaiting(false);
146 Assert.assertTrue(c.isAssignableFrom(m_threw.getClass()));
147 }
148 }
149 }