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.32 by jsr166, Sun Dec 16 18:52:27 2012 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines