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.29 by jsr166, Mon Jun 20 04:31:59 2011 UTC vs.
Revision 1.53 by jsr166, Sun Jul 22 22:13:55 2018 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 < import junit.framework.*;
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 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
26 < import static java.util.concurrent.TimeUnit.SECONDS;
27 < import java.util.*;
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);
# Line 37 | Line 44 | public class FutureTaskTest extends JSR1
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();
43            int savedSetCount = pf.setCount();
44            int savedSetExceptionCount = pf.setExceptionCount();
60              pf.run();
61              pf.runAndReset();
62              assertEquals(savedRunCount, pf.runCount());
63 <            assertEquals(savedSetCount, pf.setCount());
64 <            assertEquals(savedSetExceptionCount, pf.setExceptionCount());
63 >            Object r2 = null;
64 >            try {
65 >                r2 = f.get();
66 >            } catch (CancellationException t) {
67 >                assertSame(exInfo, CancellationException.class);
68 >            } catch (ExecutionException t) {
69 >                assertSame(exInfo, t.getCause());
70 >            } catch (Throwable t) {
71 >                threadUnexpectedException(t);
72 >            }
73 >            if (exInfo == null)
74 >                assertSame(r, r2);
75              assertTrue(f.isDone());
76          }
77      }
# Line 68 | Line 93 | public class FutureTaskTest extends JSR1
93              FutureTask ft = (FutureTask<?>) f;
94              // Check that run methods do nothing
95              ft.run();
96 <            if (f instanceof PublicFutureTask)
97 <                assertFalse(((PublicFutureTask) f).runAndReset());
96 >            if (f instanceof PublicFutureTask) {
97 >                PublicFutureTask pf = (PublicFutureTask) f;
98 >                int savedRunCount = pf.runCount();
99 >                pf.run();
100 >                assertFalse(pf.runAndReset());
101 >                assertEquals(savedRunCount, pf.runCount());
102 >            }
103              checkNotDone(f);
104          }
105      }
106  
107 <    <T> void checkCompletedNormally(Future<T> f, T expected) {
107 >    <T> void checkCompletedNormally(Future<T> f, T expectedValue) {
108          checkIsDone(f);
109          assertFalse(f.isCancelled());
110  
111 +        T v1 = null, v2 = null;
112          try {
113 <            assertSame(expected, f.get());
114 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
84 <        try {
85 <            assertSame(expected, f.get(5L, SECONDS));
113 >            v1 = f.get();
114 >            v2 = f.get(randomTimeout(), randomTimeUnit());
115          } catch (Throwable fail) { threadUnexpectedException(fail); }
116 +        assertSame(expectedValue, v1);
117 +        assertSame(expectedValue, v2);
118      }
119  
120      void checkCancelled(Future<?> f) {
# Line 97 | Line 128 | public class FutureTaskTest extends JSR1
128          } catch (Throwable fail) { threadUnexpectedException(fail); }
129  
130          try {
131 <            f.get(5L, SECONDS);
131 >            f.get(randomTimeout(), randomTimeUnit());
132              shouldThrow();
133          } catch (CancellationException success) {
134          } catch (Throwable fail) { threadUnexpectedException(fail); }
# Line 107 | Line 138 | public class FutureTaskTest extends JSR1
138          pf.set(new Object());
139          pf.setException(new Error());
140          for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
141 <            pf.cancel(true);
141 >            pf.cancel(mayInterruptIfRunning);
142          }
143      }
144  
# Line 123 | Line 154 | public class FutureTaskTest extends JSR1
154          } catch (Throwable fail) { threadUnexpectedException(fail); }
155  
156          try {
157 <            f.get(5L, SECONDS);
157 >            f.get(randomTimeout(), randomTimeUnit());
158              shouldThrow();
159          } catch (ExecutionException success) {
160              assertSame(t, success.getCause());
# Line 154 | Line 185 | public class FutureTaskTest extends JSR1
185          private PublicFutureTask(final Runnable runnable, Object result,
186                                   final AtomicInteger runCount) {
187              super(new Runnable() {
188 <                    public void run() {
189 <                        runCount.getAndIncrement();
190 <                        runnable.run();
191 <                    }}, result);
188 >                public void run() {
189 >                    runCount.getAndIncrement();
190 >                    runnable.run();
191 >                }}, result);
192              this.runCount = runCount;
193          }
194          PublicFutureTask(Callable callable) {
# Line 172 | Line 203 | public class FutureTaskTest extends JSR1
203                  }});
204              this.runCount = runCount;
205          }
206 <        public void done() {
206 >        @Override public void done() {
207              assertTrue(isDone());
208              doneCount.incrementAndGet();
209              super.done();
210          }
211 <        public boolean runAndReset() {
211 >        @Override public boolean runAndReset() {
212              runAndResetCount.incrementAndGet();
213              return super.runAndReset();
214          }
215 <        public void set(Object x) {
215 >        @Override public void set(Object x) {
216              setCount.incrementAndGet();
217              super.set(x);
218          }
219 <        public void setException(Throwable t) {
219 >        @Override public void setException(Throwable t) {
220              setExceptionCount.incrementAndGet();
221              super.setException(t);
222          }
# Line 239 | Line 270 | public class FutureTaskTest extends JSR1
270          for (int i = 0; i < 3; i++) {
271              assertTrue(task.runAndReset());
272              checkNotDone(task);
273 <            assertEquals(i+1, task.runCount());
274 <            assertEquals(i+1, task.runAndResetCount());
273 >            assertEquals(i + 1, task.runCount());
274 >            assertEquals(i + 1, task.runAndResetCount());
275              assertEquals(0, task.setCount());
276              assertEquals(0, task.setExceptionCount());
277          }
# Line 256 | Line 287 | public class FutureTaskTest extends JSR1
287              for (int i = 0; i < 3; i++) {
288                  assertFalse(task.runAndReset());
289                  assertEquals(0, task.runCount());
290 <                assertEquals(i+1, task.runAndResetCount());
290 >                assertEquals(i + 1, task.runAndResetCount());
291                  assertEquals(0, task.setCount());
292                  assertEquals(0, task.setExceptionCount());
293              }
# Line 319 | Line 350 | public class FutureTaskTest extends JSR1
350          PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
351          assertTrue(task.cancel(false));
352          task.run();
353 +        assertEquals(0, task.runCount());
354          assertEquals(0, task.setCount());
355          assertEquals(0, task.setExceptionCount());
356 +        assertTrue(task.isCancelled());
357 +        assertTrue(task.isDone());
358          tryToConfuseDoneTask(task);
325        checkCancelled(task);
359          assertEquals(0, task.runCount());
360 +        checkCancelled(task);
361      }
362  
363      /**
# Line 333 | Line 367 | public class FutureTaskTest extends JSR1
367          PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
368          assertTrue(task.cancel(true));
369          task.run();
370 +        assertEquals(0, task.runCount());
371          assertEquals(0, task.setCount());
372          assertEquals(0, task.setExceptionCount());
373 +        assertTrue(task.isCancelled());
374 +        assertTrue(task.isDone());
375          tryToConfuseDoneTask(task);
339        checkCancelled(task);
376          assertEquals(0, task.runCount());
377 +        checkCancelled(task);
378      }
379  
380      /**
# Line 347 | Line 384 | public class FutureTaskTest extends JSR1
384          PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
385          task.run();
386          assertFalse(task.cancel(false));
387 +        assertEquals(1, task.runCount());
388          assertEquals(1, task.setCount());
389          assertEquals(0, task.setExceptionCount());
390          tryToConfuseDoneTask(task);
# Line 361 | Line 399 | public class FutureTaskTest extends JSR1
399          PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
400          task.run();
401          assertFalse(task.cancel(true));
402 +        assertEquals(1, task.runCount());
403          assertEquals(1, task.setCount());
404          assertEquals(0, task.setExceptionCount());
405          tryToConfuseDoneTask(task);
# Line 381 | Line 420 | public class FutureTaskTest extends JSR1
420                          delay(LONG_DELAY_MS);
421                          shouldThrow();
422                      } catch (InterruptedException success) {}
423 +                    assertFalse(Thread.interrupted());
424                  }});
425  
426          Thread t = newStartedThread(task);
427          await(pleaseCancel);
428          assertTrue(task.cancel(true));
429          assertTrue(task.isCancelled());
430 +        assertTrue(task.isDone());
431          awaitTermination(t);
432          assertEquals(1, task.runCount());
433          assertEquals(1, task.setCount());
# Line 396 | Line 437 | public class FutureTaskTest extends JSR1
437      }
438  
439      /**
440 +     * cancel(true) tries to interrupt a running task, but
441 +     * Thread.interrupt throws (simulating a restrictive security
442 +     * manager)
443 +     */
444 +    public void testCancelInterrupt_ThrowsSecurityException() {
445 +        final CountDownLatch pleaseCancel = new CountDownLatch(1);
446 +        final CountDownLatch cancelled = new CountDownLatch(1);
447 +        final PublicFutureTask task =
448 +            new PublicFutureTask(new CheckedRunnable() {
449 +                public void realRun() {
450 +                    pleaseCancel.countDown();
451 +                    await(cancelled);
452 +                    assertFalse(Thread.interrupted());
453 +                }});
454 +
455 +        final Thread t = new Thread(task) {
456 +            // Simulate a restrictive security manager.
457 +            @Override public void interrupt() {
458 +                throw new SecurityException();
459 +            }};
460 +        t.setDaemon(true);
461 +        t.start();
462 +
463 +        await(pleaseCancel);
464 +        try {
465 +            task.cancel(true);
466 +            shouldThrow();
467 +        } catch (SecurityException success) {}
468 +
469 +        // We failed to deliver the interrupt, but the world retains
470 +        // its sanity, as if we had done task.cancel(false)
471 +        assertTrue(task.isCancelled());
472 +        assertTrue(task.isDone());
473 +        assertEquals(1, task.runCount());
474 +        assertEquals(1, task.doneCount());
475 +        assertEquals(0, task.setCount());
476 +        assertEquals(0, task.setExceptionCount());
477 +        cancelled.countDown();
478 +        awaitTermination(t);
479 +        assertEquals(1, task.setCount());
480 +        assertEquals(0, task.setExceptionCount());
481 +        tryToConfuseDoneTask(task);
482 +        checkCancelled(task);
483 +    }
484 +
485 +    /**
486       * cancel(true) interrupts a running task that subsequently throws
487       */
488      public void testCancelInterrupt_taskFails() {
# Line 403 | Line 490 | public class FutureTaskTest extends JSR1
490          final PublicFutureTask task =
491              new PublicFutureTask(new Runnable() {
492                  public void run() {
493 +                    pleaseCancel.countDown();
494                      try {
407                        pleaseCancel.countDown();
495                          delay(LONG_DELAY_MS);
496 <                    } finally { throw new RuntimeException(); }
496 >                        threadShouldThrow();
497 >                    } catch (InterruptedException success) {
498 >                    } catch (Throwable t) { threadUnexpectedException(t); }
499 >                    throw new RuntimeException();
500                  }});
501  
502          Thread t = newStartedThread(task);
# Line 531 | Line 621 | public class FutureTaskTest extends JSR1
621       * CancellationException
622       */
623      public void testTimedGet_Cancellation() {
624 <        for (final boolean mayInterruptIfRunning :
625 <                 new boolean[] { true, false }) {
626 <            final CountDownLatch pleaseCancel = new CountDownLatch(3);
627 <            final CountDownLatch cancelled = new CountDownLatch(1);
628 <            final PublicFutureTask task =
629 <                new PublicFutureTask(new CheckedCallable<Object>() {
630 <                    public Object realCall() throws InterruptedException {
631 <                        pleaseCancel.countDown();
632 <                        if (mayInterruptIfRunning) {
633 <                            try {
634 <                                delay(2*LONG_DELAY_MS);
635 <                            } catch (InterruptedException success) {}
636 <                        } else {
637 <                            await(cancelled);
638 <                        }
639 <                        return two;
640 <                    }});
624 >        testTimedGet_Cancellation(false);
625 >    }
626 >    public void testTimedGet_Cancellation_interrupt() {
627 >        testTimedGet_Cancellation(true);
628 >    }
629 >    public void testTimedGet_Cancellation(final boolean mayInterruptIfRunning) {
630 >        final CountDownLatch pleaseCancel = new CountDownLatch(3);
631 >        final CountDownLatch cancelled = new CountDownLatch(1);
632 >        final Callable<Object> callable =
633 >            new CheckedCallable<Object>() {
634 >            public Object realCall() throws InterruptedException {
635 >                pleaseCancel.countDown();
636 >                if (mayInterruptIfRunning) {
637 >                    try {
638 >                        delay(2*LONG_DELAY_MS);
639 >                    } catch (InterruptedException success) {}
640 >                } else {
641 >                    await(cancelled);
642 >                }
643 >                return two;
644 >            }};
645 >        final PublicFutureTask task = new PublicFutureTask(callable);
646  
647 <            Thread t1 = new ThreadShouldThrow(CancellationException.class) {
647 >        Thread t1 = new ThreadShouldThrow(CancellationException.class) {
648                  public void realRun() throws Exception {
649                      pleaseCancel.countDown();
650                      task.get();
651                  }};
652 <            Thread t2 = new ThreadShouldThrow(CancellationException.class) {
652 >        Thread t2 = new ThreadShouldThrow(CancellationException.class) {
653                  public void realRun() throws Exception {
654                      pleaseCancel.countDown();
655                      task.get(2*LONG_DELAY_MS, MILLISECONDS);
656                  }};
657 <            t1.start();
658 <            t2.start();
659 <            Thread t3 = newStartedThread(task);
660 <            await(pleaseCancel);
661 <            checkIsRunning(task);
662 <            task.cancel(mayInterruptIfRunning);
663 <            checkCancelled(task);
664 <            awaitTermination(t1);
665 <            awaitTermination(t2);
666 <            cancelled.countDown();
667 <            awaitTermination(t3);
668 <            assertEquals(1, task.runCount());
669 <            assertEquals(1, task.setCount());
670 <            assertEquals(0, task.setExceptionCount());
671 <            tryToConfuseDoneTask(task);
672 <            checkCancelled(task);
578 <        }
657 >        t1.start();
658 >        t2.start();
659 >        Thread t3 = newStartedThread(task);
660 >        await(pleaseCancel);
661 >        checkIsRunning(task);
662 >        task.cancel(mayInterruptIfRunning);
663 >        checkCancelled(task);
664 >        awaitTermination(t1);
665 >        awaitTermination(t2);
666 >        cancelled.countDown();
667 >        awaitTermination(t3);
668 >        assertEquals(1, task.runCount());
669 >        assertEquals(1, task.setCount());
670 >        assertEquals(0, task.setExceptionCount());
671 >        tryToConfuseDoneTask(task);
672 >        checkCancelled(task);
673      }
674  
675      /**
# Line 719 | Line 813 | public class FutureTaskTest extends JSR1
813          }
814      }
815  
816 +    /**
817 +     * timed get with most negative timeout works correctly (i.e. no
818 +     * underflow bug)
819 +     */
820 +    public void testGet_NegativeInfinityTimeout() throws Exception {
821 +        final ExecutorService pool = Executors.newFixedThreadPool(10);
822 +        final Runnable nop = new Runnable() { public void run() {}};
823 +        final FutureTask<Void> task = new FutureTask<>(nop, null);
824 +        final List<Future<?>> futures = new ArrayList<>();
825 +        Runnable r = new Runnable() { public void run() {
826 +            for (long timeout : new long[] { 0L, -1L, Long.MIN_VALUE }) {
827 +                try {
828 +                    task.get(timeout, NANOSECONDS);
829 +                    shouldThrow();
830 +                } catch (TimeoutException success) {
831 +                } catch (Throwable fail) {threadUnexpectedException(fail);}}}};
832 +        for (int i = 0; i < 10; i++)
833 +            futures.add(pool.submit(r));
834 +        try {
835 +            joinPool(pool);
836 +            for (Future<?> future : futures)
837 +                checkCompletedNormally(future, null);
838 +        } finally {
839 +            task.run();         // last resort to help terminate
840 +        }
841 +    }
842 +
843 +    /**
844 +     * toString indicates current completion state
845 +     */
846 +    public void testToString_incomplete() {
847 +        FutureTask<String> f = new FutureTask<>(() -> "");
848 +        assertTrue(f.toString().matches(".*\\[.*Not completed.*\\]"));
849 +        if (testImplementationDetails)
850 +            assertTrue(f.toString().startsWith(
851 +                               identityString(f) + "[Not completed, task ="));
852 +    }
853 +
854 +    public void testToString_normal() {
855 +        FutureTask<String> f = new FutureTask<>(() -> "");
856 +        f.run();
857 +        assertTrue(f.toString().matches(".*\\[.*Completed normally.*\\]"));
858 +        if (testImplementationDetails)
859 +            assertEquals(identityString(f) + "[Completed normally]",
860 +                         f.toString());
861 +    }
862 +
863 +    public void testToString_exception() {
864 +        FutureTask<String> f = new FutureTask<>(
865 +                () -> { throw new ArithmeticException(); });
866 +        f.run();
867 +        assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
868 +        if (testImplementationDetails)
869 +            assertTrue(f.toString().startsWith(
870 +                               identityString(f) + "[Completed exceptionally: "));
871 +    }
872 +
873 +    public void testToString_cancelled() {
874 +        for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
875 +            FutureTask<String> f = new FutureTask<>(() -> "");
876 +            assertTrue(f.cancel(mayInterruptIfRunning));
877 +            assertTrue(f.toString().matches(".*\\[.*Cancelled.*\\]"));
878 +            if (testImplementationDetails)
879 +                assertEquals(identityString(f) + "[Cancelled]",
880 +                             f.toString());
881 +        }
882 +    }
883 +
884   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines