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.21 by jsr166, Sat Oct 9 19:30:35 2010 UTC vs.
Revision 1.46 by jsr166, Mon May 29 19:15:02 2017 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines