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.25 by dl, Fri May 6 11:22:07 2011 UTC vs.
Revision 1.48 by jsr166, Sat Oct 21 06:50:25 2017 UTC

# Line 6 | Line 6
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 static java.util.concurrent.TimeUnit.SECONDS;
11 < 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 <        assertTrue(f.isDone());
105 >        checkIsDone(f);
106          assertFalse(f.isCancelled());
107  
108          try {
109              assertSame(expected, f.get());
110 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
111 <        try {
37 <            assertSame(expected, f.get(5L, SECONDS));
38 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
39 <
40 <        assertFalse(f.cancel(false));
41 <        assertFalse(f.cancel(true));
110 >            assertSame(expected, f.get(randomTimeout(), randomTimeUnit()));
111 >        } catch (Exception fail) { threadUnexpectedException(fail); }
112      }
113  
114      void checkCancelled(Future<?> f) {
115 <        assertTrue(f.isDone());
115 >        checkIsDone(f);
116          assertTrue(f.isCancelled());
117  
118          try {
# Line 52 | Line 122 | public class FutureTaskTest extends JSR1
122          } catch (Throwable fail) { threadUnexpectedException(fail); }
123  
124          try {
125 <            f.get(5L, SECONDS);
125 >            f.get(randomTimeout(), randomTimeUnit());
126              shouldThrow();
127          } catch (CancellationException success) {
128          } catch (Throwable fail) { threadUnexpectedException(fail); }
129 +    }
130  
131 <        assertFalse(f.cancel(false));
132 <        assertFalse(f.cancel(true));
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 <        assertTrue(f.isDone());
140 >        checkIsDone(f);
141          assertFalse(f.isCancelled());
142  
143          try {
# Line 73 | Line 148 | public class FutureTaskTest extends JSR1
148          } catch (Throwable fail) { threadUnexpectedException(fail); }
149  
150          try {
151 <            f.get(5L, SECONDS);
151 >            f.get(randomTimeout(), randomTimeUnit());
152              shouldThrow();
153          } catch (ExecutionException success) {
154              assertSame(t, success.getCause());
155          } catch (Throwable fail) { threadUnexpectedException(fail); }
81
82        assertFalse(f.cancel(false));
83        assertFalse(f.cancel(true));
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 117 | 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          checkCompletedNormally(task, Boolean.TRUE);
256 +        assertEquals(1, task.runCount());
257      }
258  
259      /**
# Line 128 | Line 261 | public class FutureTaskTest extends JSR1
261       */
262      public void testRunAndReset() {
263          PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
264 <        assertTrue(task.runAndReset());
265 <        checkNotDone(task);
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 <        checkCancelled(task);
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  
145
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 +            task.get();
319 +            shouldThrow();
320 +        } catch (ExecutionException success) {
321 +            assertSame(nse, success.getCause());
322 +            checkCompletedAbnormally(task, nse);
323 +        }
324 +
325          try {
326 <            Object x = task.get();
326 >            task.get(LONG_DELAY_MS, MILLISECONDS);
327              shouldThrow();
328          } catch (ExecutionException success) {
329 <            assertSame(success.getCause(), nse);
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 +        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 +        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 +        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 CountDownLatch threadStarted = new CountDownLatch(1);
394 <        final FutureTask task =
395 <            new FutureTask(new CheckedCallable<Object>() {
396 <                public Object realCall() {
397 <                    threadStarted.countDown();
398 <                    long t0 = System.nanoTime();
399 <                    for (;;) {
400 <                        if (Thread.interrupted())
401 <                            return Boolean.TRUE;
402 <                        if (millisElapsedSince(t0) > MEDIUM_DELAY_MS)
403 <                            fail("interrupt not delivered");
404 <                        Thread.yield();
405 <                    }
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 = newStartedThread(task);
421 <        threadStarted.await();
421 >        await(pleaseCancel);
422          assertTrue(task.cancel(true));
423 <        checkCancelled(task);
424 <        awaitTermination(t, MEDIUM_DELAY_MS);
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  
433      /**
434 <     * cancel(false) does not interrupt a running task
434 >     * cancel(true) tries to interrupt a running task, but
435 >     * Thread.interrupt throws (simulating a restrictive security
436 >     * manager)
437       */
438 <    public void testCancelNoInterrupt() throws InterruptedException {
439 <        final CountDownLatch threadStarted = new CountDownLatch(1);
438 >    public void testCancelInterrupt_ThrowsSecurityException() {
439 >        final CountDownLatch pleaseCancel = new CountDownLatch(1);
440          final CountDownLatch cancelled = new CountDownLatch(1);
441 <        final FutureTask<Boolean> task =
442 <            new FutureTask<Boolean>(new CheckedCallable<Boolean>() {
443 <                public Boolean realCall() throws InterruptedException {
444 <                    threadStarted.countDown();
445 <                    cancelled.await(MEDIUM_DELAY_MS, MILLISECONDS);
441 >        final PublicFutureTask task =
442 >            new PublicFutureTask(new CheckedRunnable() {
443 >                public void realRun() {
444 >                    pleaseCancel.countDown();
445 >                    await(cancelled);
446                      assertFalse(Thread.interrupted());
241                    return Boolean.TRUE;
447                  }});
448  
449 <        Thread t = newStartedThread(task);
450 <        threadStarted.await();
451 <        assertTrue(task.cancel(false));
452 <        checkCancelled(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 >
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, MEDIUM_DELAY_MS);
472 >        awaitTermination(t);
473 >        assertEquals(1, task.setCount());
474 >        assertEquals(0, task.setExceptionCount());
475 >        tryToConfuseDoneTask(task);
476          checkCancelled(task);
477      }
478  
479      /**
480 <     * run in one thread causes get in another thread to retrieve value
480 >     * cancel(true) interrupts a running task that subsequently throws
481       */
482 <    public void testGetRun() throws InterruptedException {
483 <        final CountDownLatch threadStarted = new CountDownLatch(1);
484 <
485 <        final FutureTask task =
486 <            new FutureTask(new CheckedCallable<Object>() {
487 <                public Object realCall() throws InterruptedException {
488 <                    return Boolean.TRUE;
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(new CheckedRunnable() {
497 <            public void realRun() throws Exception {
498 <                threadStarted.countDown();
499 <                assertSame(Boolean.TRUE, task.get());
500 <            }});
501 <
502 <        threadStarted.await();
503 <        checkNotDone(task);
504 <        assertTrue(t.isAlive());
505 <        task.run();
275 <        checkCompletedNormally(task, Boolean.TRUE);
276 <        awaitTermination(t, MEDIUM_DELAY_MS);
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 testGetSet() throws InterruptedException {
512 <        final CountDownLatch threadStarted = new CountDownLatch(1);
513 <
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<Object>() {
516 <                public Object realCall() throws InterruptedException {
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                  }});
522  
523 <        Thread t = newStartedThread(new CheckedRunnable() {
524 <            public void realRun() throws Exception {
525 <                threadStarted.countDown();
526 <                assertSame(Boolean.FALSE, task.get());
527 <            }});
528 <
529 <        threadStarted.await();
530 <        checkNotDone(task);
531 <        assertTrue(t.isAlive());
532 <        task.set(Boolean.FALSE);
533 <        checkCompletedNormally(task, Boolean.FALSE);
302 <        awaitTermination(t, MEDIUM_DELAY_MS);
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 <     * run 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 testTimedGetRun() throws InterruptedException {
540 <        final CountDownLatch threadStarted = new CountDownLatch(1);
539 >    public void testGetRun() {
540 >        final CountDownLatch pleaseRun = new CountDownLatch(2);
541  
542 <        final FutureTask task =
543 <            new FutureTask(new CheckedCallable<Object>() {
544 <                public Object realCall() throws InterruptedException {
545 <                    return Boolean.TRUE;
542 >        final PublicFutureTask task =
543 >            new PublicFutureTask(new CheckedCallable<Object>() {
544 >                public Object realCall() {
545 >                    return two;
546                  }});
547  
548 <        Thread t = newStartedThread(new CheckedRunnable() {
548 >        Thread t1 = newStartedThread(new CheckedRunnable() {
549 >            public void realRun() throws Exception {
550 >                pleaseRun.countDown();
551 >                assertSame(two, task.get());
552 >            }});
553 >
554 >        Thread t2 = newStartedThread(new CheckedRunnable() {
555              public void realRun() throws Exception {
556 <                threadStarted.countDown();
557 <                assertSame(Boolean.TRUE,
321 <                           task.get(MEDIUM_DELAY_MS, MILLISECONDS));
556 >                pleaseRun.countDown();
557 >                assertSame(two, task.get(2*LONG_DELAY_MS, MILLISECONDS));
558              }});
559  
560 <        threadStarted.await();
560 >        await(pleaseRun);
561          checkNotDone(task);
562 <        assertTrue(t.isAlive());
562 >        assertTrue(t1.isAlive());
563 >        assertTrue(t2.isAlive());
564          task.run();
565 <        checkCompletedNormally(task, Boolean.TRUE);
566 <        awaitTermination(t, MEDIUM_DELAY_MS);
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 <     * set in one thread causes timed get in another thread to retrieve value
576 >     * set in one thread causes get in another thread to retrieve value
577       */
578 <    public void testTimedGetSet() throws InterruptedException {
579 <        final CountDownLatch threadStarted = new CountDownLatch(1);
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 <                    return Boolean.TRUE;
584 >                    return two;
585                  }});
586  
587 <        Thread t = newStartedThread(new CheckedRunnable() {
587 >        Thread t1 = newStartedThread(new CheckedRunnable() {
588              public void realRun() throws Exception {
589 <                threadStarted.countDown();
590 <                assertSame(Boolean.FALSE,
348 <                           task.get(MEDIUM_DELAY_MS, MILLISECONDS));
589 >                pleaseSet.countDown();
590 >                assertSame(two, task.get());
591              }});
592  
593 <        threadStarted.await();
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(t.isAlive());
602 <        task.set(Boolean.FALSE);
603 <        checkCompletedNormally(task, Boolean.FALSE);
604 <        awaitTermination(t, MEDIUM_DELAY_MS);
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 timed get in another thread to throw
615       * CancellationException
616       */
617 <    public void testTimedGet_Cancellation() throws InterruptedException {
618 <        final CountDownLatch threadStarted = new CountDownLatch(2);
365 <        final FutureTask task =
366 <            new FutureTask(new CheckedInterruptedCallable<Object>() {
367 <                public Object realCall() throws InterruptedException {
368 <                    threadStarted.countDown();
369 <                    delay(LONG_DELAY_MS);
370 <                    return Boolean.TRUE;
371 <                }});
372 <
373 <        Thread t1 = new ThreadShouldThrow(CancellationException.class) {
374 <            public void realRun() throws Exception {
375 <                threadStarted.countDown();
376 <                task.get(MEDIUM_DELAY_MS, MILLISECONDS);
377 <            }};
378 <        Thread t2 = new Thread(task);
379 <        t1.start();
380 <        t2.start();
381 <        threadStarted.await();
382 <        task.cancel(true);
383 <        awaitTermination(t1, MEDIUM_DELAY_MS);
384 <        awaitTermination(t2, MEDIUM_DELAY_MS);
385 <        checkCancelled(task);
617 >    public void testTimedGet_Cancellation() {
618 >        testTimedGet_Cancellation(false);
619      }
620 <
621 <    /**
622 <     * Cancelling a task causes get in another thread to throw
623 <     * CancellationException
624 <     */
625 <    public void testGet_Cancellation() throws InterruptedException {
626 <        final CountDownLatch threadStarted = new CountDownLatch(2);
627 <        final FutureTask task =
628 <            new FutureTask(new CheckedInterruptedCallable<Object>() {
629 <                public Object realCall() throws InterruptedException {
630 <                    threadStarted.countDown();
631 <                    delay(LONG_DELAY_MS);
632 <                    return Boolean.TRUE;
633 <                }});
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 t1 = new ThreadShouldThrow(CancellationException.class) {
642 <            public void realRun() throws Exception {
643 <                threadStarted.countDown();
644 <                task.get();
645 <            }};
646 <        Thread t2 = new Thread(task);
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 <        threadStarted.await();
654 <        task.cancel(true);
655 <        awaitTermination(t1, MEDIUM_DELAY_MS);
656 <        awaitTermination(t2, MEDIUM_DELAY_MS);
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  
417
669      /**
670       * A runtime exception in task causes get to throw ExecutionException
671       */
672      public void testGet_ExecutionException() throws InterruptedException {
673 <        final FutureTask task = 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          task.run();
680 +        assertEquals(1, task.runCount());
681 +        assertEquals(0, task.setCount());
682 +        assertEquals(1, task.setExceptionCount());
683          try {
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      }
# Line 438 | 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 task = 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          task.run();
704          try {
705 <            task.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  
456
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 CountDownLatch threadStarted = new CountDownLatch(1);
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 CheckedInterruptedRunnable() {
720 >        Thread t = newStartedThread(new CheckedRunnable() {
721              public void realRun() throws Exception {
722 <                threadStarted.countDown();
723 <                task.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 <        threadStarted.await();
737 >        await(pleaseInterrupt);
738          t.interrupt();
739 <        awaitTermination(t, MEDIUM_DELAY_MS);
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 CountDownLatch threadStarted = new CountDownLatch(1);
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 CheckedInterruptedRunnable() {
749 >        Thread t = newStartedThread(new CheckedRunnable() {
750              public void realRun() throws Exception {
751 <                threadStarted.countDown();
752 <                task.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 <        threadStarted.await();
766 >        await(pleaseInterrupt);
767          t.interrupt();
768 <        awaitTermination(t, MEDIUM_DELAY_MS);
768 >        awaitTermination(t);
769          checkNotDone(task);
770      }
771  
# Line 494 | Line 773 | public class FutureTaskTest extends JSR1
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 task = new FutureTask(new NoOpCallable());
499 <            task.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 >    /**
838 >     * toString indicates current completion state
839 >     */
840 >    public void testToString_incomplete() {
841 >        FutureTask<String> f = new FutureTask<String>(() -> "");
842 >        assertTrue(f.toString().matches(".*\\[.*Not completed.*\\]"));
843 >        if (testImplementationDetails)
844 >            assertTrue(f.toString().startsWith(
845 >                               identityString(f) + "[Not completed, task ="));
846 >    }
847 >
848 >    public void testToString_normal() {
849 >        FutureTask<String> f = new FutureTask<String>(() -> "");
850 >        f.run();
851 >        assertTrue(f.toString().matches(".*\\[.*Completed normally.*\\]"));
852 >        if (testImplementationDetails)
853 >            assertEquals(identityString(f) + "[Completed normally]",
854 >                         f.toString());
855 >    }
856 >
857 >    public void testToString_exception() {
858 >        FutureTask<String> f = new FutureTask<String>(
859 >                () -> { throw new ArithmeticException(); });
860 >        f.run();
861 >        assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
862 >        if (testImplementationDetails)
863 >            assertTrue(f.toString().startsWith(
864 >                               identityString(f) + "[Completed exceptionally: "));
865 >    }
866 >
867 >    public void testToString_cancelled() {
868 >        for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
869 >            FutureTask<String> f = new FutureTask<String>(() -> "");
870 >            assertTrue(f.cancel(mayInterruptIfRunning));
871 >            assertTrue(f.toString().matches(".*\\[.*Cancelled.*\\]"));
872 >            if (testImplementationDetails)
873 >                assertEquals(identityString(f) + "[Cancelled]",
874 >                             f.toString());
875 >        }
876      }
877  
878   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines