ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/FutureTaskTest.java
(Generate patch)

Comparing jsr166/src/test/tck/FutureTaskTest.java (file contents):
Revision 1.8 by dl, Mon Dec 22 00:48:55 2003 UTC vs.
Revision 1.34 by jsr166, Sat Dec 29 19:07:32 2012 UTC

# Line 1 | Line 1
1   /*
2 < * Written by members of JCP JSR-166 Expert Group and released to the
3 < * public domain. Use, modify, and redistribute this code in any way
4 < * without acknowledgement. Other contributors include Andrew Wright,
5 < * Jeffrey Hayes, Pat Fischer, Mike Judd.
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.*;
10 > import java.util.concurrent.Callable;
11 > import java.util.concurrent.CancellationException;
12 > import java.util.concurrent.CountDownLatch;
13 > import java.util.concurrent.ExecutionException;
14 > import java.util.concurrent.Future;
15 > import java.util.concurrent.FutureTask;
16 > import java.util.concurrent.TimeoutException;
17 > import java.util.concurrent.atomic.AtomicInteger;
18 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
19 > import static java.util.concurrent.TimeUnit.SECONDS;
20   import java.util.*;
21  
22   public class FutureTaskTest extends JSR166TestCase {
23  
24      public static void main(String[] args) {
25 <        junit.textui.TestRunner.run (suite());  
25 >        junit.textui.TestRunner.run(suite());
26      }
27      public static Test suite() {
28 <        return new TestSuite(FutureTaskTest.class);
28 >        return new TestSuite(FutureTaskTest.class);
29 >    }
30 >
31 >    void checkIsDone(Future<?> f) {
32 >        assertTrue(f.isDone());
33 >        assertFalse(f.cancel(false));
34 >        assertFalse(f.cancel(true));
35 >        if (f instanceof PublicFutureTask) {
36 >            PublicFutureTask pf = (PublicFutureTask) f;
37 >            assertEquals(1, pf.doneCount());
38 >            assertFalse(pf.runAndReset());
39 >            assertEquals(1, pf.doneCount());
40 >
41 >            // Check that run and runAndReset have no effect.
42 >            int savedRunCount = pf.runCount();
43 >            int savedSetCount = pf.setCount();
44 >            int savedSetExceptionCount = pf.setExceptionCount();
45 >            pf.run();
46 >            pf.runAndReset();
47 >            assertEquals(savedRunCount, pf.runCount());
48 >            assertEquals(savedSetCount, pf.setCount());
49 >            assertEquals(savedSetExceptionCount, pf.setExceptionCount());
50 >            assertTrue(f.isDone());
51 >        }
52 >    }
53 >
54 >    void checkNotDone(Future<?> f) {
55 >        assertFalse(f.isDone());
56 >        assertFalse(f.isCancelled());
57 >        if (f instanceof PublicFutureTask) {
58 >            PublicFutureTask pf = (PublicFutureTask) f;
59 >            assertEquals(0, pf.doneCount());
60 >            assertEquals(0, pf.setCount());
61 >            assertEquals(0, pf.setExceptionCount());
62 >        }
63 >    }
64 >
65 >    void checkIsRunning(Future<?> f) {
66 >        checkNotDone(f);
67 >        if (f instanceof FutureTask) {
68 >            FutureTask ft = (FutureTask<?>) f;
69 >            // Check that run methods do nothing
70 >            ft.run();
71 >            if (f instanceof PublicFutureTask)
72 >                assertFalse(((PublicFutureTask) f).runAndReset());
73 >            checkNotDone(f);
74 >        }
75 >    }
76 >
77 >    <T> void checkCompletedNormally(Future<T> f, T expected) {
78 >        checkIsDone(f);
79 >        assertFalse(f.isCancelled());
80 >
81 >        try {
82 >            assertSame(expected, f.get());
83 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
84 >        try {
85 >            assertSame(expected, f.get(5L, SECONDS));
86 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
87 >    }
88 >
89 >    void checkCancelled(Future<?> f) {
90 >        checkIsDone(f);
91 >        assertTrue(f.isCancelled());
92 >
93 >        try {
94 >            f.get();
95 >            shouldThrow();
96 >        } catch (CancellationException success) {
97 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
98 >
99 >        try {
100 >            f.get(5L, SECONDS);
101 >            shouldThrow();
102 >        } catch (CancellationException success) {
103 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
104 >    }
105 >
106 >    void tryToConfuseDoneTask(PublicFutureTask pf) {
107 >        pf.set(new Object());
108 >        pf.setException(new Error());
109 >        for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
110 >            pf.cancel(true);
111 >        }
112 >    }
113 >
114 >    void checkCompletedAbnormally(Future<?> f, Throwable t) {
115 >        checkIsDone(f);
116 >        assertFalse(f.isCancelled());
117 >
118 >        try {
119 >            f.get();
120 >            shouldThrow();
121 >        } catch (ExecutionException success) {
122 >            assertSame(t, success.getCause());
123 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
124 >
125 >        try {
126 >            f.get(5L, SECONDS);
127 >            shouldThrow();
128 >        } catch (ExecutionException success) {
129 >            assertSame(t, success.getCause());
130 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
131      }
132  
133      /**
134       * Subclass to expose protected methods
135       */
136      static class PublicFutureTask extends FutureTask {
137 <        public PublicFutureTask(Callable r) { super(r); }
138 <        public boolean reset() { return super.reset(); }
139 <        public void setCancelled() { super.setCancelled(); }
140 <        public void set(Object x) { super.set(x); }
141 <        public void setException(Throwable t) { super.setException(t); }
137 >        private final AtomicInteger runCount;
138 >        private final AtomicInteger doneCount = new AtomicInteger(0);
139 >        private final AtomicInteger runAndResetCount = new AtomicInteger(0);
140 >        private final AtomicInteger setCount = new AtomicInteger(0);
141 >        private final AtomicInteger setExceptionCount = new AtomicInteger(0);
142 >        public int runCount() { return runCount.get(); }
143 >        public int doneCount() { return doneCount.get(); }
144 >        public int runAndResetCount() { return runAndResetCount.get(); }
145 >        public int setCount() { return setCount.get(); }
146 >        public int setExceptionCount() { return setExceptionCount.get(); }
147 >
148 >        PublicFutureTask(Runnable runnable) {
149 >            this(runnable, seven);
150 >        }
151 >        PublicFutureTask(Runnable runnable, Object result) {
152 >            this(runnable, result, new AtomicInteger(0));
153 >        }
154 >        private PublicFutureTask(final Runnable runnable, Object result,
155 >                                 final AtomicInteger runCount) {
156 >            super(new Runnable() {
157 >                public void run() {
158 >                    runCount.getAndIncrement();
159 >                    runnable.run();
160 >                }}, result);
161 >            this.runCount = runCount;
162 >        }
163 >        PublicFutureTask(Callable callable) {
164 >            this(callable, new AtomicInteger(0));
165 >        }
166 >        private PublicFutureTask(final Callable callable,
167 >                                 final AtomicInteger runCount) {
168 >            super(new Callable() {
169 >                public Object call() throws Exception {
170 >                    runCount.getAndIncrement();
171 >                    return callable.call();
172 >                }});
173 >            this.runCount = runCount;
174 >        }
175 >        @Override public void done() {
176 >            assertTrue(isDone());
177 >            doneCount.incrementAndGet();
178 >            super.done();
179 >        }
180 >        @Override public boolean runAndReset() {
181 >            runAndResetCount.incrementAndGet();
182 >            return super.runAndReset();
183 >        }
184 >        @Override public void set(Object x) {
185 >            setCount.incrementAndGet();
186 >            super.set(x);
187 >        }
188 >        @Override public void setException(Throwable t) {
189 >            setExceptionCount.incrementAndGet();
190 >            super.setException(t);
191 >        }
192 >    }
193 >
194 >    class Counter extends CheckedRunnable {
195 >        final AtomicInteger count = new AtomicInteger(0);
196 >        public int get() { return count.get(); }
197 >        public void realRun() {
198 >            count.getAndIncrement();
199 >        }
200      }
201  
202      /**
203 <     * Creating a future with a null callable throws NPE
203 >     * creating a future with a null callable throws NullPointerException
204       */
205      public void testConstructor() {
206          try {
207 <            FutureTask task = new FutureTask(null);
207 >            new FutureTask(null);
208              shouldThrow();
209 <        }
40 <        catch(NullPointerException success) {
41 <        }
209 >        } catch (NullPointerException success) {}
210      }
211  
212      /**
213 <     * creating a future with null runnable fails
213 >     * creating a future with null runnable throws NullPointerException
214       */
215      public void testConstructor2() {
216          try {
217 <            FutureTask task = new FutureTask(null, Boolean.TRUE);
217 >            new FutureTask(null, Boolean.TRUE);
218              shouldThrow();
219 <        }
52 <        catch(NullPointerException success) {
53 <        }
219 >        } catch (NullPointerException success) {}
220      }
221  
222      /**
223       * isDone is true when a task completes
224       */
225      public void testIsDone() {
60        FutureTask task = new FutureTask( new NoOpCallable());
61        task.run();
62        assertTrue(task.isDone());
63        assertFalse(task.isCancelled());
64    }
65
66    /**
67     * reset of a done task succeeds and changes status to not done
68     */
69    public void testReset() {
226          PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
71        task.run();
72        assertTrue(task.isDone());
73        assertTrue(task.reset());      
227          assertFalse(task.isDone());
228 +        task.run();
229 +        assertTrue(task.isDone());
230 +        checkCompletedNormally(task, Boolean.TRUE);
231 +        assertEquals(1, task.runCount());
232      }
233  
234      /**
235 <     * Resetting after cancellation fails
235 >     * runAndReset of a non-cancelled task succeeds
236       */
237 <    public void testResetAfterCancel() {
237 >    public void testRunAndReset() {
238          PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
239 <        assertTrue(task.cancel(false));
240 <        task.run();
241 <        assertTrue(task.isDone());
242 <        assertTrue(task.isCancelled());
243 <        assertFalse(task.reset());
239 >        for (int i = 0; i < 3; i++) {
240 >            assertTrue(task.runAndReset());
241 >            checkNotDone(task);
242 >            assertEquals(i+1, task.runCount());
243 >            assertEquals(i+1, task.runAndResetCount());
244 >            assertEquals(0, task.setCount());
245 >            assertEquals(0, task.setExceptionCount());
246 >        }
247      }
248  
89
249      /**
250 <     * setCancelled of a new task causes isCancelled to be true
250 >     * runAndReset after cancellation fails
251       */
252 <    public void testSetCancelled() {
253 <        PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
254 <        assertTrue(task.cancel(false));
255 <        task.setCancelled();
256 <        assertTrue(task.isDone());
257 <        assertTrue(task.isCancelled());
252 >    public void testRunAndResetAfterCancel() {
253 >        for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
254 >            PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
255 >            assertTrue(task.cancel(mayInterruptIfRunning));
256 >            for (int i = 0; i < 3; i++) {
257 >                assertFalse(task.runAndReset());
258 >                assertEquals(0, task.runCount());
259 >                assertEquals(i+1, task.runAndResetCount());
260 >                assertEquals(0, task.setCount());
261 >                assertEquals(0, task.setExceptionCount());
262 >            }
263 >            tryToConfuseDoneTask(task);
264 >            checkCancelled(task);
265 >        }
266      }
267  
268      /**
269 <     * setting value gauses get to return it
269 >     * setting value causes get to return it
270       */
271 <    public void testSet() {
271 >    public void testSet() throws Exception {
272          PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
273          task.set(one);
274 <        try {
275 <            assertEquals(task.get(), one);
276 <        }
277 <        catch(Exception e) {
278 <            unexpectedException();
279 <        }
274 >        for (int i = 0; i < 3; i++) {
275 >            assertSame(one, task.get());
276 >            assertSame(one, task.get(LONG_DELAY_MS, MILLISECONDS));
277 >            assertEquals(1, task.setCount());
278 >        }
279 >        tryToConfuseDoneTask(task);
280 >        checkCompletedNormally(task, one);
281 >        assertEquals(0, task.runCount());
282      }
283  
284      /**
285       * setException causes get to throw ExecutionException
286       */
287 <    public void testSetException() {
287 >    public void testSetException_get() throws Exception {
288          Exception nse = new NoSuchElementException();
289          PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
290          task.setException(nse);
291 +
292          try {
293 <            Object x = task.get();
293 >            task.get();
294              shouldThrow();
295 +        } catch (ExecutionException success) {
296 +            assertSame(nse, success.getCause());
297 +            checkCompletedAbnormally(task, nse);
298          }
299 <        catch(ExecutionException ee) {
300 <            Throwable cause = ee.getCause();
301 <            assertEquals(cause, nse);
302 <        }
303 <        catch(Exception e) {
304 <            unexpectedException();
299 >
300 >        try {
301 >            task.get(LONG_DELAY_MS, MILLISECONDS);
302 >            shouldThrow();
303 >        } catch (ExecutionException success) {
304 >            assertSame(nse, success.getCause());
305 >            checkCompletedAbnormally(task, nse);
306          }
307 +
308 +        assertEquals(1, task.setExceptionCount());
309 +        assertEquals(0, task.setCount());
310 +        tryToConfuseDoneTask(task);
311 +        checkCompletedAbnormally(task, nse);
312 +        assertEquals(0, task.runCount());
313      }
314  
315      /**
316 <     *  Cancelling before running succeeds
316 >     * cancel(false) before run succeeds
317       */
318      public void testCancelBeforeRun() {
319 <        FutureTask task = new FutureTask( new NoOpCallable());
319 >        PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
320          assertTrue(task.cancel(false));
321 <        task.run();
322 <        assertTrue(task.isDone());
323 <        assertTrue(task.isCancelled());
321 >        task.run();
322 >        assertEquals(0, task.runCount());
323 >        assertEquals(0, task.setCount());
324 >        assertEquals(0, task.setExceptionCount());
325 >        assertTrue(task.isCancelled());
326 >        assertTrue(task.isDone());
327 >        tryToConfuseDoneTask(task);
328 >        assertEquals(0, task.runCount());
329 >        checkCancelled(task);
330      }
331  
332      /**
333 <     * Cancel(true) before run succeeds
333 >     * cancel(true) before run succeeds
334       */
335      public void testCancelBeforeRun2() {
336 <        FutureTask task = new FutureTask( new NoOpCallable());
336 >        PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
337          assertTrue(task.cancel(true));
338 <        task.run();
339 <        assertTrue(task.isDone());
340 <        assertTrue(task.isCancelled());
338 >        task.run();
339 >        assertEquals(0, task.runCount());
340 >        assertEquals(0, task.setCount());
341 >        assertEquals(0, task.setExceptionCount());
342 >        assertTrue(task.isCancelled());
343 >        assertTrue(task.isDone());
344 >        tryToConfuseDoneTask(task);
345 >        assertEquals(0, task.runCount());
346 >        checkCancelled(task);
347      }
348  
349      /**
350 <     * cancel of a completed task fails
350 >     * cancel(false) of a completed task fails
351       */
352      public void testCancelAfterRun() {
353 <        FutureTask task = new FutureTask( new NoOpCallable());
354 <        task.run();
353 >        PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
354 >        task.run();
355          assertFalse(task.cancel(false));
356 <        assertTrue(task.isDone());
357 <        assertFalse(task.isCancelled());
356 >        assertEquals(1, task.runCount());
357 >        assertEquals(1, task.setCount());
358 >        assertEquals(0, task.setExceptionCount());
359 >        tryToConfuseDoneTask(task);
360 >        checkCompletedNormally(task, Boolean.TRUE);
361 >        assertEquals(1, task.runCount());
362      }
363  
364      /**
365 <     * cancel(true) interrupts a running task
365 >     * cancel(true) of a completed task fails
366 >     */
367 >    public void testCancelAfterRun2() {
368 >        PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
369 >        task.run();
370 >        assertFalse(task.cancel(true));
371 >        assertEquals(1, task.runCount());
372 >        assertEquals(1, task.setCount());
373 >        assertEquals(0, task.setExceptionCount());
374 >        tryToConfuseDoneTask(task);
375 >        checkCompletedNormally(task, Boolean.TRUE);
376 >        assertEquals(1, task.runCount());
377 >    }
378 >
379 >    /**
380 >     * cancel(true) interrupts a running task that subsequently succeeds
381       */
382      public void testCancelInterrupt() {
383 <        FutureTask task = new FutureTask( new Callable() {
384 <                public Object call() {
383 >        final CountDownLatch pleaseCancel = new CountDownLatch(1);
384 >        final PublicFutureTask task =
385 >            new PublicFutureTask(new CheckedRunnable() {
386 >                public void realRun() {
387 >                    pleaseCancel.countDown();
388                      try {
389 <                        Thread.sleep(MEDIUM_DELAY_MS);
390 <                        threadShouldThrow();
391 <                    }
392 <                    catch (InterruptedException success) {}
393 <                    return Boolean.TRUE;
394 <                } });
395 <        Thread t = new  Thread(task);
389 >                        delay(LONG_DELAY_MS);
390 >                        shouldThrow();
391 >                    } catch (InterruptedException success) {}
392 >                }});
393 >
394 >        Thread t = newStartedThread(task);
395 >        await(pleaseCancel);
396 >        assertTrue(task.cancel(true));
397 >        assertTrue(task.isCancelled());
398 >        assertTrue(task.isDone());
399 >        awaitTermination(t);
400 >        assertEquals(1, task.runCount());
401 >        assertEquals(1, task.setCount());
402 >        assertEquals(0, task.setExceptionCount());
403 >        tryToConfuseDoneTask(task);
404 >        checkCancelled(task);
405 >    }
406 >
407 >    /**
408 >     * cancel(true) tries to interrupt a running task, but
409 >     * Thread.interrupt throws (simulating a restrictive security
410 >     * manager)
411 >     */
412 >    public void testCancelInterrupt_ThrowsSecurityException() {
413 >        final CountDownLatch pleaseCancel = new CountDownLatch(1);
414 >        final CountDownLatch cancelled = new CountDownLatch(1);
415 >        final PublicFutureTask task =
416 >            new PublicFutureTask(new CheckedRunnable() {
417 >                public void realRun() {
418 >                    pleaseCancel.countDown();
419 >                    await(cancelled);
420 >                    assertFalse(Thread.interrupted());
421 >                }});
422 >
423 >        final Thread t = new Thread(task) {
424 >            // Simulate a restrictive security manager.
425 >            @Override public void interrupt() {
426 >                throw new SecurityException();
427 >            }};
428 >        t.setDaemon(true);
429          t.start();
430 <        
430 >
431 >        await(pleaseCancel);
432          try {
433 <            Thread.sleep(SHORT_DELAY_MS);
434 <            assertTrue(task.cancel(true));
435 <            t.join();
436 <            assertTrue(task.isDone());
437 <            assertTrue(task.isCancelled());
438 <        } catch(InterruptedException e){
439 <            unexpectedException();
440 <        }
433 >            task.cancel(true);
434 >            shouldThrow();
435 >        } catch (SecurityException expected) {}
436 >
437 >        // We failed to deliver the interrupt, but the world retains
438 >        // its sanity, as if we had done task.cancel(false)
439 >        assertTrue(task.isCancelled());
440 >        assertTrue(task.isDone());
441 >        assertEquals(1, task.runCount());
442 >        assertEquals(1, task.doneCount());
443 >        assertEquals(0, task.setCount());
444 >        assertEquals(0, task.setExceptionCount());
445 >        cancelled.countDown();
446 >        awaitTermination(t);
447 >        assertEquals(1, task.setCount());
448 >        assertEquals(0, task.setExceptionCount());
449 >        tryToConfuseDoneTask(task);
450 >        checkCancelled(task);
451      }
452  
453 +    /**
454 +     * cancel(true) interrupts a running task that subsequently throws
455 +     */
456 +    public void testCancelInterrupt_taskFails() {
457 +        final CountDownLatch pleaseCancel = new CountDownLatch(1);
458 +        final PublicFutureTask task =
459 +            new PublicFutureTask(new Runnable() {
460 +                public void run() {
461 +                    try {
462 +                        pleaseCancel.countDown();
463 +                        delay(LONG_DELAY_MS);
464 +                    } finally { throw new RuntimeException(); }
465 +                }});
466 +
467 +        Thread t = newStartedThread(task);
468 +        await(pleaseCancel);
469 +        assertTrue(task.cancel(true));
470 +        assertTrue(task.isCancelled());
471 +        awaitTermination(t);
472 +        assertEquals(1, task.runCount());
473 +        assertEquals(0, task.setCount());
474 +        assertEquals(1, task.setExceptionCount());
475 +        tryToConfuseDoneTask(task);
476 +        checkCancelled(task);
477 +    }
478  
479      /**
480       * cancel(false) does not interrupt a running task
481       */
482      public void testCancelNoInterrupt() {
483 <        FutureTask task = new FutureTask( new Callable() {
484 <                public Object call() {
485 <                    try {
486 <                        Thread.sleep(MEDIUM_DELAY_MS);
487 <                    }
488 <                    catch (InterruptedException success) {
489 <                        threadFail("should not interrupt");
490 <                    }
483 >        final CountDownLatch pleaseCancel = new CountDownLatch(1);
484 >        final CountDownLatch cancelled = new CountDownLatch(1);
485 >        final PublicFutureTask task =
486 >            new PublicFutureTask(new CheckedCallable<Boolean>() {
487 >                public Boolean realCall() {
488 >                    pleaseCancel.countDown();
489 >                    await(cancelled);
490 >                    assertFalse(Thread.interrupted());
491                      return Boolean.TRUE;
492 <                } });
493 <        Thread t = new  Thread(task);
494 <        t.start();
495 <        
496 <        try {
497 <            Thread.sleep(SHORT_DELAY_MS);
498 <            assertTrue(task.cancel(false));
499 <            t.join();
500 <            assertTrue(task.isDone());
501 <            assertTrue(task.isCancelled());
502 <        } catch(InterruptedException e){
503 <            unexpectedException();
504 <        }
492 >                }});
493 >
494 >        Thread t = newStartedThread(task);
495 >        await(pleaseCancel);
496 >        assertTrue(task.cancel(false));
497 >        assertTrue(task.isCancelled());
498 >        cancelled.countDown();
499 >        awaitTermination(t);
500 >        assertEquals(1, task.runCount());
501 >        assertEquals(1, task.setCount());
502 >        assertEquals(0, task.setExceptionCount());
503 >        tryToConfuseDoneTask(task);
504 >        checkCancelled(task);
505      }
506  
507      /**
508 <     * set in one thread causes get in another thread to retrieve value
509 <     */
510 <    public void testGet1() {
511 <        final FutureTask ft = new FutureTask(new Callable() {
512 <                public Object call() {
513 <                    try {
514 <                        Thread.sleep(MEDIUM_DELAY_MS);
515 <                    } catch(InterruptedException e){
516 <                        threadUnexpectedException();
517 <                    }
518 <                    return Boolean.TRUE;
519 <                }
520 <        });
521 <        Thread t = new Thread(new Runnable() {
522 <                public void run() {
523 <                    try {
524 <                        ft.get();
525 <                    } catch(Exception e){
526 <                        threadUnexpectedException();
527 <                    }
528 <                }
529 <            });
530 <        try {
531 <            assertFalse(ft.isDone());
532 <            assertFalse(ft.isCancelled());
533 <            t.start();
534 <            Thread.sleep(SHORT_DELAY_MS);
535 <            ft.run();
536 <            t.join();
537 <            assertTrue(ft.isDone());
538 <            assertFalse(ft.isCancelled());
539 <        } catch(InterruptedException e){
540 <            unexpectedException();
541 <
542 <        }      
508 >     * run in one thread causes get in another thread to retrieve value
509 >     */
510 >    public void testGetRun() {
511 >        final CountDownLatch pleaseRun = new CountDownLatch(2);
512 >
513 >        final PublicFutureTask task =
514 >            new PublicFutureTask(new CheckedCallable<Object>() {
515 >                public Object realCall() {
516 >                    return two;
517 >                }});
518 >
519 >        Thread t1 = newStartedThread(new CheckedRunnable() {
520 >            public void realRun() throws Exception {
521 >                pleaseRun.countDown();
522 >                assertSame(two, task.get());
523 >            }});
524 >
525 >        Thread t2 = newStartedThread(new CheckedRunnable() {
526 >            public void realRun() throws Exception {
527 >                pleaseRun.countDown();
528 >                assertSame(two, task.get(2*LONG_DELAY_MS, MILLISECONDS));
529 >            }});
530 >
531 >        await(pleaseRun);
532 >        checkNotDone(task);
533 >        assertTrue(t1.isAlive());
534 >        assertTrue(t2.isAlive());
535 >        task.run();
536 >        checkCompletedNormally(task, two);
537 >        assertEquals(1, task.runCount());
538 >        assertEquals(1, task.setCount());
539 >        assertEquals(0, task.setExceptionCount());
540 >        awaitTermination(t1);
541 >        awaitTermination(t2);
542 >        tryToConfuseDoneTask(task);
543 >        checkCompletedNormally(task, two);
544      }
545  
546      /**
547 <     * set in one thread causes timed get in another thread to retrieve value
548 <     */
549 <    public void testTimedGet1() {
550 <        final FutureTask ft = new FutureTask(new Callable() {
551 <                public Object call() {
552 <                    try {
553 <                        Thread.sleep(MEDIUM_DELAY_MS);
554 <                    } catch(InterruptedException e){
555 <                        threadUnexpectedException();
556 <                    }
557 <                    return Boolean.TRUE;
558 <                }
559 <            });
560 <        Thread t = new Thread(new Runnable() {
561 <                public void run() {
562 <                    try {
563 <                        ft.get(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
564 <                    } catch(TimeoutException success) {
565 <                    } catch(Exception e){
566 <                        threadUnexpectedException();
567 <                    }
568 <                }
569 <            });
570 <        try {
571 <            assertFalse(ft.isDone());
572 <            assertFalse(ft.isCancelled());
573 <            t.start();
574 <            ft.run();
575 <            t.join();
576 <            assertTrue(ft.isDone());
577 <            assertFalse(ft.isCancelled());
578 <        } catch(InterruptedException e){
579 <            unexpectedException();
580 <            
581 <        }      
547 >     * set in one thread causes get in another thread to retrieve value
548 >     */
549 >    public void testGetSet() {
550 >        final CountDownLatch pleaseSet = new CountDownLatch(2);
551 >
552 >        final PublicFutureTask task =
553 >            new PublicFutureTask(new CheckedCallable<Object>() {
554 >                public Object realCall() throws InterruptedException {
555 >                    return two;
556 >                }});
557 >
558 >        Thread t1 = newStartedThread(new CheckedRunnable() {
559 >            public void realRun() throws Exception {
560 >                pleaseSet.countDown();
561 >                assertSame(two, task.get());
562 >            }});
563 >
564 >        Thread t2 = newStartedThread(new CheckedRunnable() {
565 >            public void realRun() throws Exception {
566 >                pleaseSet.countDown();
567 >                assertSame(two, task.get(2*LONG_DELAY_MS, MILLISECONDS));
568 >            }});
569 >
570 >        await(pleaseSet);
571 >        checkNotDone(task);
572 >        assertTrue(t1.isAlive());
573 >        assertTrue(t2.isAlive());
574 >        task.set(two);
575 >        assertEquals(0, task.runCount());
576 >        assertEquals(1, task.setCount());
577 >        assertEquals(0, task.setExceptionCount());
578 >        tryToConfuseDoneTask(task);
579 >        checkCompletedNormally(task, two);
580 >        awaitTermination(t1);
581 >        awaitTermination(t2);
582      }
583  
584      /**
585 <     *  Cancelling a task causes timed get in another thread to throw CancellationException
585 >     * Cancelling a task causes timed get in another thread to throw
586 >     * CancellationException
587       */
588      public void testTimedGet_Cancellation() {
589 <        final FutureTask ft = new FutureTask(new Callable() {
590 <                public Object call() {
591 <                    try {
592 <                        Thread.sleep(SMALL_DELAY_MS);
593 <                        threadShouldThrow();
594 <                    } catch(InterruptedException e) {
595 <                    }
596 <                    return Boolean.TRUE;
597 <                }
598 <            });
599 <        try {
600 <            Thread t1 = new Thread(new Runnable() {
601 <                    public void run() {
602 <                        try {
603 <                            ft.get(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
604 <                            threadShouldThrow();
605 <                        } catch(CancellationException success) {}
606 <                        catch(Exception e){
607 <                            threadUnexpectedException();
608 <                        }
609 <                    }
610 <                });
611 <            Thread t2 = new Thread(ft);
612 <            t1.start();
589 >        for (final boolean mayInterruptIfRunning :
590 >                 new boolean[] { true, false }) {
591 >            final CountDownLatch pleaseCancel = new CountDownLatch(3);
592 >            final CountDownLatch cancelled = new CountDownLatch(1);
593 >            final PublicFutureTask task =
594 >                new PublicFutureTask(new CheckedCallable<Object>() {
595 >                    public Object realCall() throws InterruptedException {
596 >                        pleaseCancel.countDown();
597 >                        if (mayInterruptIfRunning) {
598 >                            try {
599 >                                delay(2*LONG_DELAY_MS);
600 >                            } catch (InterruptedException success) {}
601 >                        } else {
602 >                            await(cancelled);
603 >                        }
604 >                        return two;
605 >                    }});
606 >
607 >            Thread t1 = new ThreadShouldThrow(CancellationException.class) {
608 >                public void realRun() throws Exception {
609 >                    pleaseCancel.countDown();
610 >                    task.get();
611 >                }};
612 >            Thread t2 = new ThreadShouldThrow(CancellationException.class) {
613 >                public void realRun() throws Exception {
614 >                    pleaseCancel.countDown();
615 >                    task.get(2*LONG_DELAY_MS, MILLISECONDS);
616 >                }};
617 >            t1.start();
618              t2.start();
619 <            Thread.sleep(SHORT_DELAY_MS);
620 <            ft.cancel(true);
621 <            t1.join();
622 <            t2.join();
623 <        } catch(InterruptedException ie){
624 <            unexpectedException();
619 >            Thread t3 = newStartedThread(task);
620 >            await(pleaseCancel);
621 >            checkIsRunning(task);
622 >            task.cancel(mayInterruptIfRunning);
623 >            checkCancelled(task);
624 >            awaitTermination(t1);
625 >            awaitTermination(t2);
626 >            cancelled.countDown();
627 >            awaitTermination(t3);
628 >            assertEquals(1, task.runCount());
629 >            assertEquals(1, task.setCount());
630 >            assertEquals(0, task.setExceptionCount());
631 >            tryToConfuseDoneTask(task);
632 >            checkCancelled(task);
633          }
634      }
635  
636      /**
637 <     * Cancelling a task causes get in another thread to throw CancellationException
638 <     */
639 <    public void testGet_Cancellation() {
640 <        final FutureTask ft = new FutureTask(new Callable() {
641 <                public Object call() {
642 <                    try {
643 <                        Thread.sleep(MEDIUM_DELAY_MS);
644 <                        threadShouldThrow();
645 <                    } catch(InterruptedException e){
646 <                    }
647 <                    return Boolean.TRUE;
648 <                }
649 <            });
650 <        try {
651 <            Thread t1 = new Thread(new Runnable() {
652 <                    public void run() {
653 <                        try {
654 <                            ft.get();
655 <                            threadShouldThrow();
656 <                        } catch(CancellationException success){
359 <                        }
360 <                        catch(Exception e){
361 <                            threadUnexpectedException();
362 <                        }
363 <                    }
364 <                });
365 <            Thread t2 = new Thread(ft);
366 <            t1.start();
367 <            t2.start();
368 <            Thread.sleep(SHORT_DELAY_MS);
369 <            ft.cancel(true);
370 <            t1.join();
371 <            t2.join();
372 <        } catch(InterruptedException success){
373 <            unexpectedException();
637 >     * A runtime exception in task causes get to throw ExecutionException
638 >     */
639 >    public void testGet_ExecutionException() throws InterruptedException {
640 >        final ArithmeticException e = new ArithmeticException();
641 >        final PublicFutureTask task = new PublicFutureTask(new Callable() {
642 >            public Object call() {
643 >                throw e;
644 >            }});
645 >
646 >        task.run();
647 >        assertEquals(1, task.runCount());
648 >        assertEquals(0, task.setCount());
649 >        assertEquals(1, task.setExceptionCount());
650 >        try {
651 >            task.get();
652 >            shouldThrow();
653 >        } catch (ExecutionException success) {
654 >            assertSame(e, success.getCause());
655 >            tryToConfuseDoneTask(task);
656 >            checkCompletedAbnormally(task, success.getCause());
657          }
658      }
376    
659  
660      /**
661 <     * A runtime exception in task causes get to throw ExecutionException
661 >     * A runtime exception in task causes timed get to throw ExecutionException
662       */
663 <    public void testGet_ExecutionException() {
664 <        final FutureTask ft = new FutureTask(new Callable() {
665 <                public Object call() {
666 <                    int i = 5/0;
667 <                    return Boolean.TRUE;
668 <                }
669 <            });
670 <        try {
671 <            ft.run();
672 <            ft.get();
673 <            shouldThrow();
674 <        } catch(ExecutionException success){
675 <        }
676 <        catch(Exception e){
677 <            unexpectedException();
396 <        }
397 <    }
398 <  
399 <    /**
400 <     *  A runtime exception in task causes timed get to throw ExecutionException
401 <     */
402 <    public void testTimedGet_ExecutionException2() {
403 <        final FutureTask ft = new FutureTask(new Callable() {
404 <                public Object call() {
405 <                    int i = 5/0;
406 <                    return Boolean.TRUE;
407 <                }
408 <            });
409 <        try {
410 <            ft.run();
411 <            ft.get(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
412 <            shouldThrow();
413 <        } catch(ExecutionException success) {
414 <        } catch(TimeoutException success) { } // unlikely but OK
415 <        catch(Exception e){
416 <            unexpectedException();
417 <        }
418 <    }
419 <      
420 <
421 <    /**
422 <     * Interrupting a waiting get causes it to throw InterruptedException
423 <     */
424 <    public void testGet_InterruptedException() {
425 <        final FutureTask ft = new FutureTask(new NoOpCallable());
426 <        Thread t = new Thread(new Runnable() {
427 <                public void run() {                
428 <                    try {
429 <                        ft.get();
430 <                        threadShouldThrow();
431 <                    } catch(InterruptedException success){
432 <                    } catch(Exception e){
433 <                        threadUnexpectedException();
434 <                    }
435 <                }
436 <            });
437 <        try {
438 <            t.start();
439 <            Thread.sleep(SHORT_DELAY_MS);
440 <            t.interrupt();
441 <            t.join();
442 <        } catch(Exception e){
443 <            unexpectedException();
444 <        }
445 <    }
446 <
447 <    /**
448 <     *  Interrupting a waiting timed get causes it to throw InterruptedException
449 <     */
450 <    public void testTimedGet_InterruptedException2() {
451 <        final FutureTask ft = new FutureTask(new NoOpCallable());
452 <        Thread t = new Thread(new Runnable() {
453 <                public void run() {                
454 <                    try {
455 <                        ft.get(LONG_DELAY_MS,TimeUnit.MILLISECONDS);
456 <                        threadShouldThrow();
457 <                    } catch(InterruptedException success){}
458 <                    catch(Exception e){
459 <                        threadUnexpectedException();
460 <                    }
461 <                }
462 <            });
463 <        try {
464 <            t.start();
465 <            Thread.sleep(SHORT_DELAY_MS);
466 <            t.interrupt();
467 <            t.join();
468 <        } catch(Exception e){
469 <            unexpectedException();
663 >    public void testTimedGet_ExecutionException2() throws Exception {
664 >        final ArithmeticException e = new ArithmeticException();
665 >        final PublicFutureTask task = new PublicFutureTask(new Callable() {
666 >            public Object call() {
667 >                throw e;
668 >            }});
669 >
670 >        task.run();
671 >        try {
672 >            task.get(LONG_DELAY_MS, MILLISECONDS);
673 >            shouldThrow();
674 >        } catch (ExecutionException success) {
675 >            assertSame(e, success.getCause());
676 >            tryToConfuseDoneTask(task);
677 >            checkCompletedAbnormally(task, success.getCause());
678          }
679      }
680 <    
680 >
681 >    /**
682 >     * get is interruptible
683 >     */
684 >    public void testGet_interruptible() {
685 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
686 >        final FutureTask task = new FutureTask(new NoOpCallable());
687 >        Thread t = newStartedThread(new CheckedRunnable() {
688 >            public void realRun() throws Exception {
689 >                Thread.currentThread().interrupt();
690 >                try {
691 >                    task.get();
692 >                    shouldThrow();
693 >                } catch (InterruptedException success) {}
694 >                assertFalse(Thread.interrupted());
695 >
696 >                pleaseInterrupt.countDown();
697 >                try {
698 >                    task.get();
699 >                    shouldThrow();
700 >                } catch (InterruptedException success) {}
701 >                assertFalse(Thread.interrupted());
702 >            }});
703 >
704 >        await(pleaseInterrupt);
705 >        t.interrupt();
706 >        awaitTermination(t);
707 >        checkNotDone(task);
708 >    }
709 >
710 >    /**
711 >     * timed get is interruptible
712 >     */
713 >    public void testTimedGet_interruptible() {
714 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
715 >        final FutureTask task = new FutureTask(new NoOpCallable());
716 >        Thread t = newStartedThread(new CheckedRunnable() {
717 >            public void realRun() throws Exception {
718 >                Thread.currentThread().interrupt();
719 >                try {
720 >                    task.get(2*LONG_DELAY_MS, MILLISECONDS);
721 >                    shouldThrow();
722 >                } catch (InterruptedException success) {}
723 >                assertFalse(Thread.interrupted());
724 >
725 >                pleaseInterrupt.countDown();
726 >                try {
727 >                    task.get(2*LONG_DELAY_MS, MILLISECONDS);
728 >                    shouldThrow();
729 >                } catch (InterruptedException success) {}
730 >                assertFalse(Thread.interrupted());
731 >            }});
732 >
733 >        await(pleaseInterrupt);
734 >        t.interrupt();
735 >        awaitTermination(t);
736 >        checkNotDone(task);
737 >    }
738 >
739      /**
740       * A timed out timed get throws TimeoutException
741       */
742 <    public void testGet_TimeoutException() {
743 <        try {
744 <            FutureTask ft = new FutureTask(new NoOpCallable());
745 <            ft.get(1,TimeUnit.MILLISECONDS);
746 <            shouldThrow();
747 <        } catch(TimeoutException success){}
748 <        catch(Exception success){
749 <            unexpectedException();
750 <        }
742 >    public void testGet_TimeoutException() throws Exception {
743 >        FutureTask task = new FutureTask(new NoOpCallable());
744 >        long startTime = System.nanoTime();
745 >        try {
746 >            task.get(timeoutMillis(), MILLISECONDS);
747 >            shouldThrow();
748 >        } catch (TimeoutException success) {
749 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
750 >        }
751      }
752 <    
752 >
753 >    /**
754 >     * timed get with null TimeUnit throws NullPointerException
755 >     */
756 >    public void testGet_NullTimeUnit() throws Exception {
757 >        FutureTask task = new FutureTask(new NoOpCallable());
758 >        long[] timeouts = { Long.MIN_VALUE, 0L, Long.MAX_VALUE };
759 >
760 >        for (long timeout : timeouts) {
761 >            try {
762 >                task.get(timeout, null);
763 >                shouldThrow();
764 >            } catch (NullPointerException success) {}
765 >        }
766 >
767 >        task.run();
768 >
769 >        for (long timeout : timeouts) {
770 >            try {
771 >                task.get(timeout, null);
772 >                shouldThrow();
773 >            } catch (NullPointerException success) {}
774 >        }
775 >    }
776 >
777   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines