44import static java .lang .Math .atan ;
55import static java .lang .System .currentTimeMillis ;
66import static java .lang .Thread .currentThread ;
7+ import static java .lang .Thread .interrupted ;
78import static java .lang .Thread .sleep ;
89import static java .util .concurrent .TimeUnit .MILLISECONDS ;
910import static org .junit .Assert .assertEquals ;
1718import static org .junit .Assume .assumeTrue ;
1819
1920import java .util .Arrays ;
21+ import java .util .concurrent .CountDownLatch ;
2022import java .util .concurrent .atomic .AtomicBoolean ;
2123import java .util .concurrent .atomic .AtomicReference ;
2224
@@ -114,19 +116,17 @@ public void throwsExceptionWithTimeoutValueAndTimeUnitSet() {
114116
115117 @ Test
116118 public void statementThatCanBeInterruptedIsStoppedAfterTimeout () throws Throwable {
117- // RunForASecond can be interrupted because it uses Thread.sleep which
118- // can be interrupted.
119+ // RunForASecond can be interrupted because it checks the Thread's
120+ // interrupted flag .
119121 RunForASecond runForASecond = new RunForASecond ();
120122 assertThrows (
121123 TestTimedOutException .class ,
122124 run (failAfter50Ms (runForASecond )));
123125
124- sleep (20 ); // time to interrupt the thread
125- runForASecond .stillExecuting .set (false );
126- sleep (20 ); // time to increment the count
127- assertFalse (
128- "Thread has not been stopped." ,
129- runForASecond .stillExecuting .get ());
126+ // Thread is explicitly stopped if it finishes faster than its
127+ // pre-defined execution time of one second.
128+ boolean stopped = runForASecond .finished .await (50 , MILLISECONDS );
129+ assertTrue ("Thread has not been stopped." , stopped );
130130 }
131131
132132 @ Test
@@ -243,7 +243,7 @@ public void run() throws Throwable {
243243 }
244244
245245 private static class DelegatingStatement extends Statement {
246- Statement delegate ;
246+ volatile Statement delegate ;
247247
248248 @ Override
249249 public void evaluate () throws Throwable {
@@ -258,15 +258,14 @@ public void evaluate() throws Throwable {
258258 }
259259
260260 private static final class RunForASecond extends Statement {
261- final AtomicBoolean stillExecuting = new AtomicBoolean ( );
261+ final CountDownLatch finished = new CountDownLatch ( 1 );
262262
263263 @ Override
264264 public void evaluate () throws Throwable {
265265 long timeout = currentTimeMillis () + 1000L ;
266- while (currentTimeMillis () < timeout ) {
267- sleep (10 ); // sleep in order to enable interrupting thread
268- stillExecuting .set (true );
266+ while (!interrupted () && currentTimeMillis () < timeout ) {
269267 }
268+ finished .countDown ();
270269 }
271270 }
272271}
0 commit comments