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.4 by dl, Sun Sep 14 20:42:40 2003 UTC vs.
Revision 1.51 by jsr166, Sun Jan 7 22:59:18 2018 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.*;
11 < import java.util.*;
9 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
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);
35 >        return new TestSuite(FutureTaskTest.class);
36      }
37  
38 <    /**
39 <     * Subclass to expose protected methods
40 <     */
41 <    static class MyFutureTask extends FutureTask {
42 <        public MyFutureTask(Callable r) { super(r); }
43 <        public boolean reset() { return super.reset(); }
44 <        public void setCancelled() { super.setCancelled(); }
45 <        public void setDone() { super.setDone(); }
46 <        public void set(Object x) { super.set(x); }
47 <        public void setException(Throwable t) { super.setException(t); }
38 >    void checkIsDone(Future<?> f) {
39 >        assertTrue(f.isDone());
40 >        assertFalse(f.cancel(false));
41 >        assertFalse(f.cancel(true));
42 >        if (f instanceof PublicFutureTask) {
43 >            PublicFutureTask pf = (PublicFutureTask) f;
44 >            assertEquals(1, pf.doneCount());
45 >            assertFalse(pf.runAndReset());
46 >            assertEquals(1, pf.doneCount());
47 >            Object r = null; Object exInfo = null;
48 >            try {
49 >                r = f.get();
50 >            } catch (CancellationException t) {
51 >                exInfo = CancellationException.class;
52 >            } catch (ExecutionException t) {
53 >                exInfo = t.getCause();
54 >            } catch (Throwable t) {
55 >                threadUnexpectedException(t);
56 >            }
57 >
58 >            // Check that run and runAndReset have no effect.
59 >            int savedRunCount = pf.runCount();
60 >            pf.run();
61 >            pf.runAndReset();
62 >            assertEquals(savedRunCount, pf.runCount());
63 >            try {
64 >                assertSame(r, f.get());
65 >            } catch (CancellationException t) {
66 >                assertSame(exInfo, CancellationException.class);
67 >            } catch (ExecutionException t) {
68 >                assertSame(exInfo, t.getCause());
69 >            } catch (Throwable t) {
70 >                threadUnexpectedException(t);
71 >            }
72 >            assertTrue(f.isDone());
73 >        }
74 >    }
75 >
76 >    void checkNotDone(Future<?> f) {
77 >        assertFalse(f.isDone());
78 >        assertFalse(f.isCancelled());
79 >        if (f instanceof PublicFutureTask) {
80 >            PublicFutureTask pf = (PublicFutureTask) f;
81 >            assertEquals(0, pf.doneCount());
82 >            assertEquals(0, pf.setCount());
83 >            assertEquals(0, pf.setExceptionCount());
84 >        }
85 >    }
86 >
87 >    void checkIsRunning(Future<?> f) {
88 >        checkNotDone(f);
89 >        if (f instanceof FutureTask) {
90 >            FutureTask ft = (FutureTask<?>) f;
91 >            // Check that run methods do nothing
92 >            ft.run();
93 >            if (f instanceof PublicFutureTask) {
94 >                PublicFutureTask pf = (PublicFutureTask) f;
95 >                int savedRunCount = pf.runCount();
96 >                pf.run();
97 >                assertFalse(pf.runAndReset());
98 >                assertEquals(savedRunCount, pf.runCount());
99 >            }
100 >            checkNotDone(f);
101 >        }
102 >    }
103 >
104 >    <T> void checkCompletedNormally(Future<T> f, T expected) {
105 >        checkIsDone(f);
106 >        assertFalse(f.isCancelled());
107 >
108 >        try {
109 >            assertSame(expected, f.get());
110 >            assertSame(expected, f.get(randomTimeout(), randomTimeUnit()));
111 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
112      }
113  
114 <    public void testConstructor(){
114 >    void checkCancelled(Future<?> f) {
115 >        checkIsDone(f);
116 >        assertTrue(f.isCancelled());
117 >
118          try {
119 <            FutureTask task = new FutureTask(null);
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 testConstructor2(){
139 >    void checkCompletedAbnormally(Future<?> f, Throwable t) {
140 >        checkIsDone(f);
141 >        assertFalse(f.isCancelled());
142 >
143          try {
144 <            FutureTask task = new FutureTask(null, Boolean.TRUE);
145 <            fail("should throw");
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 <        catch(NullPointerException success) {
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 <    public void testIsDone(){
228 <        FutureTask task = new FutureTask( new NoOpCallable());
229 <        task.run();
230 <        assertTrue(task.isDone());
231 <        assertFalse(task.isCancelled());
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 <    public void testReset(){
238 <        MyFutureTask task = new MyFutureTask(new NoOpCallable());
239 <        task.run();
240 <        assertTrue(task.isDone());
241 <        assertTrue(task.reset());
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 <    public void testResetAfterCancel() {
248 <        MyFutureTask task = new MyFutureTask(new NoOpCallable());
249 <        assertTrue(task.cancel(false));
250 <        task.run();
251 <        assertTrue(task.isDone());
252 <        assertTrue(task.isCancelled());
253 <        assertFalse(task.reset());
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 <    public void testSetDone() {
260 <        MyFutureTask task = new MyFutureTask(new NoOpCallable());
261 <        task.setDone();
262 <        assertTrue(task.isDone());
263 <        assertFalse(task.isCancelled());
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 <    public void testSetCancelled() {
275 <        MyFutureTask task = new MyFutureTask(new NoOpCallable());
276 <        assertTrue(task.cancel(false));
277 <        task.setCancelled();
278 <        assertTrue(task.isDone());
279 <        assertTrue(task.isCancelled());
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 <    public void testSet() {
294 <        MyFutureTask task = new MyFutureTask(new NoOpCallable());
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 <        try {
300 <            assertEquals(task.get(), one);
301 <        }
302 <        catch(Exception e) {
303 <            fail("unexpected exception");
304 <        }
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 <    public void testSetException() {
309 >    /**
310 >     * setException causes get to throw ExecutionException
311 >     */
312 >    public void testSetException_get() throws Exception {
313          Exception nse = new NoSuchElementException();
314 <        MyFutureTask task = new MyFutureTask(new NoOpCallable());
314 >        PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
315          task.setException(nse);
316 +
317          try {
318 <            Object x = task.get();
319 <            fail("should throw");
320 <        }
321 <        catch(ExecutionException ee) {
322 <            Throwable cause = ee.getCause();
110 <            assertEquals(cause, nse);
318 >            task.get();
319 >            shouldThrow();
320 >        } catch (ExecutionException success) {
321 >            assertSame(nse, success.getCause());
322 >            checkCompletedAbnormally(task, nse);
323          }
324 <        catch(Exception e) {
325 <            fail("unexpected exception");
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 NoOpCallable());
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 NoOpCallable());
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 NoOpCallable());
379 <        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());
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 <    public void testCancelInterrupt(){
390 <        FutureTask task = new FutureTask( new Callable() {
391 <                public Object call() {
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 <                        Thread.sleep(MEDIUM_DELAY_MS);
415 <                        threadFail("should throw");
416 <                    }
417 <                    catch (InterruptedException success) {}
418 <                    return Boolean.TRUE;
419 <                } });
420 <        Thread t = new  Thread(task);
421 <        t.start();
422 <        
423 <        try{
424 <            Thread.sleep(SHORT_DELAY_MS);
425 <            assertTrue(task.cancel(true));
426 <            t.join();
427 <            assertTrue(task.isDone());
428 <            assertTrue(task.isCancelled());
429 <        } catch(InterruptedException e){
430 <            fail("unexpected exception");
162 <        }
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 testCancelNoInterrupt(){
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(MEDIUM_DELAY_MS);
490 <                    }
491 <                    catch (InterruptedException success) {
492 <                        threadFail("should not interrupt");
493 <                    }
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(false));
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 <    public void testGet1() {
694 <        final FutureTask ft = new FutureTask(new Callable(){
695 <                public Object call(){
696 <                    try{
697 <                        Thread.sleep(MEDIUM_DELAY_MS);
698 <                    } catch(InterruptedException e){
699 <                        threadFail("unexpected exception");
700 <                    }
701 <                    return Boolean.TRUE;
702 <                }
703 <        });
704 <        Thread t = new Thread(new Runnable(){
705 <                public void run(){
706 <                    try{
707 <                        ft.get();
708 <                    } catch(Exception e){
709 <                        threadFail("unexpected exception");
710 <                    }
711 <                }
712 <            });
713 <        try{
714 <            assertFalse(ft.isDone());
715 <            assertFalse(ft.isCancelled());
716 <            t.start();
717 <            Thread.sleep(SHORT_DELAY_MS);
718 <            ft.run();
719 <            t.join();
720 <            assertTrue(ft.isDone());
721 <            assertFalse(ft.isCancelled());
722 <        } catch(InterruptedException e){
723 <            fail("unexpected exception");
724 <
725 <        }      
726 <    }
727 <
728 <    public void testTimedGet1() {
729 <        final FutureTask ft = new FutureTask(new Callable(){
730 <                public Object call(){
731 <                    try{
732 <                        Thread.sleep(MEDIUM_DELAY_MS);
733 <                    } catch(InterruptedException e){
734 <                        threadFail("unexpected exception");
735 <                    }
736 <                    return Boolean.TRUE;
737 <                }
738 <            });
739 <        Thread t = new Thread(new Runnable(){
740 <                public void run(){
239 <                    try{
240 <                        ft.get(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
241 <                    } catch(TimeoutException success) {
242 <                    } catch(Exception e){
243 <                        threadFail("unexpected exception");
244 <                    }
245 <                }
246 <            });
247 <        try{
248 <            assertFalse(ft.isDone());
249 <            assertFalse(ft.isCancelled());
250 <            t.start();
251 <            ft.run();
252 <            t.join();
253 <            assertTrue(ft.isDone());
254 <            assertFalse(ft.isCancelled());
255 <        } catch(InterruptedException e){
256 <            fail("unexpected exception");
257 <            
258 <        }      
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 >        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 <    public void testGet_Cancellation(){
773 <        final FutureTask ft = new FutureTask(new Callable(){
774 <                public Object call(){
775 <                    try{
776 <                        Thread.sleep(MEDIUM_DELAY_MS);
777 <                    } catch(InterruptedException e){
778 <                        threadFail("unexpected exception");
779 <                    }
780 <                    return Boolean.TRUE;
781 <                }
782 <            });
783 <        try {
274 <            Thread.sleep(SHORT_DELAY_MS);
275 <            Thread t = new Thread(new Runnable(){
276 <                    public void run(){
277 <                        try{
278 <                            ft.get();
279 <                            threadFail("should throw");
280 <                        } catch(CancellationException success){
281 <                        }
282 <                        catch(Exception e){
283 <                            threadFail("unexpected exception");
284 <                        }
285 <                    }
286 <                });
287 <            t.start();
288 <            ft.cancel(true);
289 <            t.join();
290 <        } catch(InterruptedException success){
291 <            fail("unexpected exception");
292 <        }
293 <    }
294 <    
295 <    public void testGet_Cancellation2(){
296 <        final FutureTask ft = new FutureTask(new Callable(){
297 <                public Object call(){
298 <                    try{
299 <                        Thread.sleep(SHORT_DELAY_MS);
300 <                    } catch(InterruptedException e) {
301 <                        threadFail("unexpected exception");
302 <                    }
303 <                    return Boolean.TRUE;
304 <                }
305 <            });
306 <        try{
307 <            Thread.sleep(SHORT_DELAY_MS);
308 <            Thread t = new Thread(new Runnable(){
309 <                    public void run(){
310 <                        try{
311 <                            ft.get(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS);
312 <                            threadFail("should throw");
313 <                        } catch(CancellationException success) {}
314 <                        catch(Exception e){
315 <                            threadFail("unexpected exception");
316 <                        }
317 <                    }
318 <                });
319 <            t.start();
320 <            Thread.sleep(SHORT_DELAY_MS);
321 <            ft.cancel(true);
322 <            Thread.sleep(SHORT_DELAY_MS);
323 <            t.join();
324 <        } catch(InterruptedException ie){
325 <            fail("unexpected exception");
326 <        }
327 <    }
328 <
329 <    public void testGet_ExecutionException(){
330 <        final FutureTask ft = new FutureTask(new Callable(){
331 <                public Object call(){
332 <                    int i = 5/0;
333 <                    return Boolean.TRUE;
334 <                }
335 <            });
336 <        try{
337 <            ft.run();
338 <            ft.get();
339 <            fail("should throw");
340 <        } catch(ExecutionException success){
341 <        }
342 <        catch(Exception e){
343 <            fail("unexpected exception");
344 <        }
345 <    }
346 <  
347 <    public void testTimedGet_ExecutionException2(){
348 <        final FutureTask ft = new FutureTask(new Callable(){
349 <                public Object call(){
350 <                    int i = 5/0;
351 <                    return Boolean.TRUE;
352 <                }
353 <            });
354 <        try{
355 <            ft.run();
356 <            ft.get(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
357 <            fail("should throw");
358 <        } catch(ExecutionException success) {
359 <        } catch(TimeoutException success) { } // unlikely but OK
360 <        catch(Exception e){
361 <            fail("unexpected exception");
362 <        }
363 <    }
364 <      
365 <
366 <    public void testGet_InterruptedException(){
367 <        final FutureTask ft = new FutureTask(new NoOpCallable());
368 <        Thread t = new Thread(new Runnable(){
369 <                public void run(){                  
370 <                    try{
371 <                        ft.get();
372 <                        threadFail("should throw");
373 <                    } catch(InterruptedException success){
374 <                    } catch(Exception e){
375 <                        threadFail("unexpected exception");
376 <                    }
377 <                }
378 <            });
379 <        try {
380 <            t.start();
381 <            Thread.sleep(SHORT_DELAY_MS);
382 <            t.interrupt();
383 <            t.join();
384 <        } catch(Exception e){
385 <            fail("unexpected exception");
386 <        }
387 <    }
388 <
389 <    public void testTimedGet_InterruptedException2(){
390 <        final FutureTask ft = new FutureTask(new NoOpCallable());
391 <        Thread t = new Thread(new Runnable(){
392 <                public void run(){                  
393 <                    try{
394 <                        ft.get(LONG_DELAY_MS,TimeUnit.MILLISECONDS);
395 <                        threadFail("should throw");
396 <                    } catch(InterruptedException success){}
397 <                    catch(Exception e){
398 <                        threadFail("unexpected exception");
399 <                    }
400 <                }
401 <            });
402 <        try {
403 <            t.start();
404 <            Thread.sleep(SHORT_DELAY_MS);
405 <            t.interrupt();
406 <            t.join();
407 <        } catch(Exception e){
408 <            fail("unexpected exception");
409 <        }
410 <    }
411 <    
412 <    public void testGet_TimeoutException(){
413 <        try{
414 <            FutureTask ft = new FutureTask(new NoOpCallable());
415 <            ft.get(1,TimeUnit.MILLISECONDS);
416 <            fail("should throw");
417 <        } catch(TimeoutException success){}
418 <        catch(Exception success){
419 <            fail("unexpected exception");
420 <        }
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 <    
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<>(() -> "");
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<>(() -> "");
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<>(
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<>(() -> "");
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