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.3 by dl, Fri Sep 12 15:40:25 2003 UTC vs.
Revision 1.50 by jsr166, Wed Nov 8 02:21:43 2017 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.*;
9 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
11  
12 < public class FutureTaskTest extends TestCase {
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);
35 >        return new TestSuite(FutureTaskTest.class);
36      }
37  
38 <    private static long SHORT_DELAY_MS = 100;
39 <    private static long MEDIUM_DELAY_MS = 1000;
40 <    private static long LONG_DELAY_MS = 10000;
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  
24    public void testConstructor(){
108          try {
109 <            FutureTask task = new FutureTask(null);
110 <            fail("should throw");
111 <        }
29 <        catch(NullPointerException success) {
30 <        }
109 >            assertSame(expected, f.get());
110 >            assertSame(expected, f.get(randomTimeout(), randomTimeUnit()));
111 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
112      }
113  
114 <    public void testConstructor2(){
114 >    void checkCancelled(Future<?> f) {
115 >        checkIsDone(f);
116 >        assertTrue(f.isCancelled());
117 >
118          try {
119 <            FutureTask task = new FutureTask(null, Boolean.TRUE);
120 <            fail("should throw");
121 <        }
122 <        catch(NullPointerException success) {
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 <    public void testIsDone(){
140 <        FutureTask task = new FutureTask( new Callable() {
141 <                public Object call() { return Boolean.TRUE; } });
142 <        task.run();
143 <        assertTrue(task.isDone());
144 <        assertFalse(task.isCancelled());
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 >        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 NullPointerException
229 >     */
230 >    public void testConstructor() {
231 >        try {
232 >            new FutureTask(null);
233 >            shouldThrow();
234 >        } catch (NullPointerException success) {}
235      }
236  
237 +    /**
238 +     * creating a future with null runnable throws NullPointerException
239 +     */
240 +    public void testConstructor2() {
241 +        try {
242 +            new FutureTask(null, Boolean.TRUE);
243 +            shouldThrow();
244 +        } catch (NullPointerException success) {}
245 +    }
246 +
247 +    /**
248 +     * isDone is true when a task completes
249 +     */
250 +    public void testIsDone() {
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 +    /**
260 +     * runAndReset of a non-cancelled task succeeds
261 +     */
262 +    public void testRunAndReset() {
263 +        PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
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 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 +
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 +        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_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 +            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 +     * cancel(false) before run succeeds
342 +     */
343      public void testCancelBeforeRun() {
344 <        FutureTask task = new FutureTask( new Callable() {
52 <                public Object call() { return Boolean.TRUE; } });
344 >        PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
345          assertTrue(task.cancel(false));
346 <        task.run();
347 <        assertTrue(task.isDone());
348 <        assertTrue(task.isCancelled());
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
359 +     */
360      public void testCancelBeforeRun2() {
361 <        FutureTask task = new FutureTask( new Callable() {
61 <                public Object call() { return Boolean.TRUE; } });
361 >        PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
362          assertTrue(task.cancel(true));
363 <        task.run();
364 <        assertTrue(task.isDone());
365 <        assertTrue(task.isCancelled());
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(false) of a completed task fails
376 +     */
377      public void testCancelAfterRun() {
378 <        FutureTask task = new FutureTask( new Callable() {
379 <                public Object call() { return Boolean.TRUE; } });
71 <        task.run();
378 >        PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
379 >        task.run();
380          assertFalse(task.cancel(false));
381 <        assertTrue(task.isDone());
382 <        assertFalse(task.isCancelled());
383 <    }
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) of a completed task fails
391 >     */
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 >        await(pleaseCancel);
422 >        assertTrue(task.cancel(true));
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(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 >        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 <    public void testCancelInterrupt(){
458 <        FutureTask task = new FutureTask( new Callable() {
459 <                public Object call() {
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 <                        Thread.sleep(SHORT_DELAY_MS* 2);
490 <                        fail("should throw");
491 <                    }
492 <                    catch (InterruptedException success) {}
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 >     * cancel(false) does not interrupt a running task
510 >     */
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 <                } });
522 <        Thread t = new  Thread(task);
523 <        t.start();
524 <        
525 <        try{
526 <            Thread.sleep(SHORT_DELAY_MS);
527 <            assertTrue(task.cancel(true));
528 <            t.join();
529 <            assertTrue(task.isDone());
530 <            assertTrue(task.isCancelled());
531 <        } catch(InterruptedException e){
532 <            fail("unexpected exception");
521 >                }});
522 >
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 get in another thread to retrieve value
538 >     */
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 >
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 >                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 >     * set in one thread causes get in another thread to retrieve value
577 >     */
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 two;
585 >                }});
586 >
587 >        Thread t1 = newStartedThread(new CheckedRunnable() {
588 >            public void realRun() throws Exception {
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 timed get in another thread to throw
615 >     * CancellationException
616 >     */
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 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 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 >
669 >    /**
670 >     * A runtime exception in task causes get to throw ExecutionException
671 >     */
672 >    public void testGet_ExecutionException() throws InterruptedException {
673 >        final ArithmeticException e = new ArithmeticException();
674 >        final PublicFutureTask task = new PublicFutureTask(new Callable() {
675 >            public Object call() {
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 >            assertSame(e, success.getCause());
688 >            tryToConfuseDoneTask(task);
689 >            checkCompletedAbnormally(task, success.getCause());
690          }
691      }
692  
693 +    /**
694 +     * A runtime exception in task causes timed get to throw ExecutionException
695 +     */
696 +    public void testTimedGet_ExecutionException2() throws Exception {
697 +        final ArithmeticException e = new ArithmeticException();
698 +        final PublicFutureTask task = new PublicFutureTask(new Callable() {
699 +            public Object call() {
700 +                throw e;
701 +            }});
702  
703 <    public void testCancelNoInterrupt(){
704 <        FutureTask task = new FutureTask( new Callable() {
705 <                public Object call() {
706 <                    try {
707 <                        Thread.sleep(SHORT_DELAY_MS* 2);
708 <                    }
709 <                    catch (InterruptedException success) {
710 <                        fail("should not interrupt");
711 <                    }
712 <                    return Boolean.TRUE;
713 <                } });
714 <        Thread t = new  Thread(task);
715 <        t.start();
716 <        
717 <        try{
718 <            Thread.sleep(SHORT_DELAY_MS);
719 <            assertTrue(task.cancel(false));
720 <            t.join();
721 <            assertTrue(task.isDone());
722 <            assertTrue(task.isCancelled());
723 <        } catch(InterruptedException e){
724 <            fail("unexpected exception");
703 >        task.run();
704 >        try {
705 >            task.get(LONG_DELAY_MS, MILLISECONDS);
706 >            shouldThrow();
707 >        } catch (ExecutionException success) {
708 >            assertSame(e, success.getCause());
709 >            tryToConfuseDoneTask(task);
710 >            checkCompletedAbnormally(task, success.getCause());
711 >        }
712 >    }
713 >
714 >    /**
715 >     * get is interruptible
716 >     */
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 >                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 >        await(pleaseInterrupt);
738 >        t.interrupt();
739 >        awaitTermination(t);
740 >        checkNotDone(task);
741 >    }
742 >
743 >    /**
744 >     * timed get is interruptible
745 >     */
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 >                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 >        await(pleaseInterrupt);
767 >        t.interrupt();
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 >            task.get(timeoutMillis(), MILLISECONDS);
780 >            shouldThrow();
781 >        } catch (TimeoutException success) {
782 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
783          }
784      }
785  
786 <    public void testGet1() {
787 <        final FutureTask ft = new FutureTask(new Callable(){
788 <                public Object call(){
789 <                    try{
790 <                        Thread.sleep(MEDIUM_DELAY_MS);
791 <                    } catch(InterruptedException e){
792 <                        fail("unexpected exception");
793 <                    }
794 <                    return Boolean.TRUE;
795 <                }
796 <        });
797 <        Thread t = new Thread(new Runnable(){
798 <                public void run(){
799 <                    try{
800 <                        ft.get();
801 <                    } catch(Exception e){
802 <                        fail("unexpected exception");
803 <                    }
804 <                }
805 <            });
806 <        try{
807 <            assertFalse(ft.isDone());
149 <            assertFalse(ft.isCancelled());
150 <            t.start();
151 <            Thread.sleep(SHORT_DELAY_MS);
152 <            ft.run();
153 <            t.join();
154 <            assertTrue(ft.isDone());
155 <            assertFalse(ft.isCancelled());
156 <        } catch(InterruptedException e){
157 <            fail("unexpected exception");
158 <
159 <        }      
160 <    }
161 <
162 <    public void testTimedGet1() {
163 <        final FutureTask ft = new FutureTask(new Callable(){
164 <                public Object call(){
165 <                    try{
166 <                        Thread.sleep(MEDIUM_DELAY_MS);
167 <                    } catch(InterruptedException e){
168 <                        fail("unexpected exception");
169 <                    }
170 <                    return Boolean.TRUE;
171 <                }
172 <            });
173 <        Thread t = new Thread(new Runnable(){
174 <                public void run(){
175 <                    try{
176 <                        ft.get(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
177 <                    } catch(TimeoutException success) {
178 <                    } catch(Exception e){
179 <                        fail("unexpected exception");
180 <                    }
181 <                }
182 <            });
183 <        try{
184 <            assertFalse(ft.isDone());
185 <            assertFalse(ft.isCancelled());
186 <            t.start();
187 <            ft.run();
188 <            t.join();
189 <            assertTrue(ft.isDone());
190 <            assertFalse(ft.isCancelled());
191 <        } catch(InterruptedException e){
192 <            fail("unexpected exception");
193 <            
194 <        }      
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 <    public void testGet_Cancellation(){
838 <        final FutureTask ft = new FutureTask(new Callable(){
839 <                public Object call(){
840 <                    try{
841 <                        Thread.sleep(MEDIUM_DELAY_MS);
842 <                    } catch(InterruptedException e){
843 <                        fail("unexpected exception");
844 <                    }
845 <                    return Boolean.TRUE;
846 <                }
847 <            });
848 <        try {
849 <            Thread.sleep(SHORT_DELAY_MS);
850 <            Thread t = new Thread(new Runnable(){
851 <                    public void run(){
852 <                        try{
853 <                            ft.get();
854 <                            fail("should throw");
855 <                        } catch(CancellationException success){
856 <                        }
857 <                        catch(Exception e){
858 <                            fail("unexpected exception");
859 <                        }
860 <                    }
861 <                });
862 <            t.start();
863 <            ft.cancel(true);
864 <            t.join();
865 <        } catch(InterruptedException success){
866 <            fail("unexpected exception");
867 <        }
868 <    }
869 <    
870 <    public void testGet_Cancellation2(){
871 <        final FutureTask ft = new FutureTask(new Callable(){
872 <                public Object call(){
873 <                    try{
874 <                        Thread.sleep(SHORT_DELAY_MS);
875 <                    } catch(InterruptedException e) {
237 <                        fail("unexpected exception");
238 <                    }
239 <                    return Boolean.TRUE;
240 <                }
241 <            });
242 <        try{
243 <            Thread.sleep(100);
244 <            Thread t = new Thread(new Runnable(){
245 <                    public void run(){
246 <                        try{
247 <                            ft.get(3 * SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
248 <                            fail("should throw");
249 <                        } catch(CancellationException success) {}
250 <                        catch(Exception e){
251 <                            fail("unexpected exception");
252 <                        }
253 <                    }
254 <                });
255 <            t.start();
256 <            Thread.sleep(SHORT_DELAY_MS);
257 <            ft.cancel(true);
258 <            Thread.sleep(SHORT_DELAY_MS);
259 <            t.join();
260 <        } catch(InterruptedException ie){
261 <            fail("unexpected exception");
262 <        }
263 <    }
264 <
265 <    public void testGet_ExecutionException(){
266 <        final FutureTask ft = new FutureTask(new Callable(){
267 <                public Object call(){
268 <                    int i = 5/0;
269 <                    return Boolean.TRUE;
270 <                }
271 <            });
272 <        try{
273 <            ft.run();
274 <            ft.get();
275 <            fail("should throw");
276 <        } catch(ExecutionException success){
277 <        }
278 <        catch(Exception e){
279 <            fail("unexpected exception");
280 <        }
281 <    }
282 <  
283 <    public void testTimedGet_ExecutionException2(){
284 <        final FutureTask ft = new FutureTask(new Callable(){
285 <                public Object call(){
286 <                    int i = 5/0;
287 <                    return Boolean.TRUE;
288 <                }
289 <            });
290 <        try{
291 <            ft.run();
292 <            ft.get(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
293 <            fail("should throw");
294 <        } catch(ExecutionException success) {
295 <        } catch(TimeoutException success) { } // unlikely but OK
296 <        catch(Exception e){
297 <            fail("unexpected exception");
298 <        }
299 <    }
300 <      
301 <
302 <    public void testGet_InterruptedException(){
303 <        final FutureTask ft = new FutureTask(new Callable(){
304 <                public Object call(){
305 <                    return new Object();
306 <                }
307 <            });
308 <        Thread t = new Thread(new Runnable(){
309 <                public void run(){                  
310 <                    try{
311 <                        ft.get();
312 <                        fail("should throw");
313 <                    } catch(InterruptedException success){
314 <                    } catch(Exception e){
315 <                        fail("unexpected exception");
316 <                    }
317 <                }
318 <            });
319 <        try {
320 <            t.start();
321 <            Thread.sleep(SHORT_DELAY_MS);
322 <            t.interrupt();
323 <            t.join();
324 <        } catch(Exception e){
325 <            fail("unexpected exception");
326 <        }
327 <    }
328 <
329 <    public void testTimedGet_InterruptedException2(){
330 <        final FutureTask ft = new FutureTask(new Callable(){
331 <                public Object call(){
332 <                    return new Object();
333 <                }
334 <            });
335 <        Thread t = new Thread(new Runnable(){
336 <                public void run(){                  
337 <                    try{
338 <                        ft.get(100,TimeUnit.SECONDS);
339 <                        fail("should throw");
340 <                    } catch(InterruptedException success){}
341 <                    catch(Exception e){
342 <                        fail("unexpected exception");
343 <                    }
344 <                }
345 <            });
346 <        try {
347 <            t.start();
348 <            Thread.sleep(SHORT_DELAY_MS);
349 <            t.interrupt();
350 <            t.join();
351 <        } catch(Exception e){
352 <            fail("unexpected exception");
353 <        }
354 <    }
355 <    
356 <    public void testGet_TimeoutException(){
357 <        FutureTask ft = new FutureTask(new Callable(){
358 <                public Object call(){
359 <                    return new Object();
360 <                }
361 <            });
362 <        try{
363 <            ft.get(1,TimeUnit.MILLISECONDS);
364 <            fail("should throw");
365 <        } catch(TimeoutException success){}
366 <        catch(Exception success){
367 <            fail("unexpected exception");
368 <        }
369 <        
370 <        
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 <    
877 >
878   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines