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.30 by jsr166, Sat Dec 15 21:48:32 2012 UTC vs.
Revision 1.48 by jsr166, Sat Oct 21 06:50:25 2017 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 < import junit.framework.*;
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 >            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      }
# Line 68 | Line 90 | public class FutureTaskTest extends JSR1
90              FutureTask ft = (FutureTask<?>) f;
91              // Check that run methods do nothing
92              ft.run();
93 <            if (f instanceof PublicFutureTask)
94 <                assertFalse(((PublicFutureTask) f).runAndReset());
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      }
# Line 80 | Line 107 | public class FutureTaskTest extends JSR1
107  
108          try {
109              assertSame(expected, f.get());
110 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
111 <        try {
85 <            assertSame(expected, f.get(5L, SECONDS));
86 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
110 >            assertSame(expected, f.get(randomTimeout(), randomTimeUnit()));
111 >        } catch (Exception fail) { threadUnexpectedException(fail); }
112      }
113  
114      void checkCancelled(Future<?> f) {
# Line 97 | Line 122 | public class FutureTaskTest extends JSR1
122          } catch (Throwable fail) { threadUnexpectedException(fail); }
123  
124          try {
125 <            f.get(5L, SECONDS);
125 >            f.get(randomTimeout(), randomTimeUnit());
126              shouldThrow();
127          } catch (CancellationException success) {
128          } catch (Throwable fail) { threadUnexpectedException(fail); }
# Line 107 | Line 132 | public class FutureTaskTest extends JSR1
132          pf.set(new Object());
133          pf.setException(new Error());
134          for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
135 <            pf.cancel(true);
135 >            pf.cancel(mayInterruptIfRunning);
136          }
137      }
138  
# Line 123 | Line 148 | public class FutureTaskTest extends JSR1
148          } catch (Throwable fail) { threadUnexpectedException(fail); }
149  
150          try {
151 <            f.get(5L, SECONDS);
151 >            f.get(randomTimeout(), randomTimeUnit());
152              shouldThrow();
153          } catch (ExecutionException success) {
154              assertSame(t, success.getCause());
# Line 154 | Line 179 | public class FutureTaskTest extends JSR1
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);
182 >                public void run() {
183 >                    runCount.getAndIncrement();
184 >                    runnable.run();
185 >                }}, result);
186              this.runCount = runCount;
187          }
188          PublicFutureTask(Callable callable) {
# Line 239 | Line 264 | public class FutureTaskTest extends JSR1
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());
267 >            assertEquals(i + 1, task.runCount());
268 >            assertEquals(i + 1, task.runAndResetCount());
269              assertEquals(0, task.setCount());
270              assertEquals(0, task.setExceptionCount());
271          }
# Line 256 | Line 281 | public class FutureTaskTest extends JSR1
281              for (int i = 0; i < 3; i++) {
282                  assertFalse(task.runAndReset());
283                  assertEquals(0, task.runCount());
284 <                assertEquals(i+1, task.runAndResetCount());
284 >                assertEquals(i + 1, task.runAndResetCount());
285                  assertEquals(0, task.setCount());
286                  assertEquals(0, task.setExceptionCount());
287              }
# Line 319 | Line 344 | public class FutureTaskTest extends JSR1
344          PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
345          assertTrue(task.cancel(false));
346          task.run();
347 +        assertEquals(0, task.runCount());
348          assertEquals(0, task.setCount());
349          assertEquals(0, task.setExceptionCount());
350 +        assertTrue(task.isCancelled());
351 +        assertTrue(task.isDone());
352          tryToConfuseDoneTask(task);
325        checkCancelled(task);
353          assertEquals(0, task.runCount());
354 +        checkCancelled(task);
355      }
356  
357      /**
# Line 333 | Line 361 | public class FutureTaskTest extends JSR1
361          PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
362          assertTrue(task.cancel(true));
363          task.run();
364 +        assertEquals(0, task.runCount());
365          assertEquals(0, task.setCount());
366          assertEquals(0, task.setExceptionCount());
367 +        assertTrue(task.isCancelled());
368 +        assertTrue(task.isDone());
369          tryToConfuseDoneTask(task);
339        checkCancelled(task);
370          assertEquals(0, task.runCount());
371 +        checkCancelled(task);
372      }
373  
374      /**
# Line 347 | Line 378 | public class FutureTaskTest extends JSR1
378          PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
379          task.run();
380          assertFalse(task.cancel(false));
381 +        assertEquals(1, task.runCount());
382          assertEquals(1, task.setCount());
383          assertEquals(0, task.setExceptionCount());
384          tryToConfuseDoneTask(task);
# Line 361 | Line 393 | public class FutureTaskTest extends JSR1
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);
# Line 381 | Line 414 | public class FutureTaskTest extends JSR1
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());
# Line 396 | Line 431 | public class FutureTaskTest extends JSR1
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 +        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() {
# Line 403 | Line 484 | public class FutureTaskTest extends JSR1
484          final PublicFutureTask task =
485              new PublicFutureTask(new Runnable() {
486                  public void run() {
487 +                    pleaseCancel.countDown();
488                      try {
407                        pleaseCancel.countDown();
489                          delay(LONG_DELAY_MS);
490 <                    } finally { throw new RuntimeException(); }
490 >                        threadShouldThrow();
491 >                    } catch (InterruptedException success) {
492 >                    } catch (Throwable t) { threadUnexpectedException(t); }
493 >                    throw new RuntimeException();
494                  }});
495  
496          Thread t = newStartedThread(task);
# Line 531 | Line 615 | public class FutureTaskTest extends JSR1
615       * CancellationException
616       */
617      public void testTimedGet_Cancellation() {
618 <        for (final boolean mayInterruptIfRunning :
619 <                 new boolean[] { true, false }) {
620 <            final CountDownLatch pleaseCancel = new CountDownLatch(3);
621 <            final CountDownLatch cancelled = new CountDownLatch(1);
622 <            final PublicFutureTask task =
623 <                new PublicFutureTask(new CheckedCallable<Object>() {
624 <                    public Object realCall() throws InterruptedException {
625 <                        pleaseCancel.countDown();
626 <                        if (mayInterruptIfRunning) {
627 <                            try {
628 <                                delay(2*LONG_DELAY_MS);
629 <                            } catch (InterruptedException success) {}
630 <                        } else {
631 <                            await(cancelled);
632 <                        }
633 <                        return two;
634 <                    }});
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) {
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) {
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);
578 <        }
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      /**
# Line 719 | Line 807 | public class FutureTaskTest extends JSR1
807          }
808      }
809  
810 +    /**
811 +     * timed get with most negative timeout works correctly (i.e. no
812 +     * underflow bug)
813 +     */
814 +    public void testGet_NegativeInfinityTimeout() throws Exception {
815 +        final ExecutorService pool = Executors.newFixedThreadPool(10);
816 +        final Runnable nop = new Runnable() { public void run() {}};
817 +        final FutureTask<Void> task = new FutureTask<>(nop, null);
818 +        final List<Future<?>> futures = new ArrayList<>();
819 +        Runnable r = new Runnable() { public void run() {
820 +            for (long timeout : new long[] { 0L, -1L, Long.MIN_VALUE }) {
821 +                try {
822 +                    task.get(timeout, NANOSECONDS);
823 +                    shouldThrow();
824 +                } catch (TimeoutException success) {
825 +                } catch (Throwable fail) {threadUnexpectedException(fail);}}}};
826 +        for (int i = 0; i < 10; i++)
827 +            futures.add(pool.submit(r));
828 +        try {
829 +            joinPool(pool);
830 +            for (Future<?> future : futures)
831 +                checkCompletedNormally(future, null);
832 +        } finally {
833 +            task.run();         // last resort to help terminate
834 +        }
835 +    }
836 +
837 +    /**
838 +     * toString indicates current completion state
839 +     */
840 +    public void testToString_incomplete() {
841 +        FutureTask<String> f = new FutureTask<String>(() -> "");
842 +        assertTrue(f.toString().matches(".*\\[.*Not completed.*\\]"));
843 +        if (testImplementationDetails)
844 +            assertTrue(f.toString().startsWith(
845 +                               identityString(f) + "[Not completed, task ="));
846 +    }
847 +
848 +    public void testToString_normal() {
849 +        FutureTask<String> f = new FutureTask<String>(() -> "");
850 +        f.run();
851 +        assertTrue(f.toString().matches(".*\\[.*Completed normally.*\\]"));
852 +        if (testImplementationDetails)
853 +            assertEquals(identityString(f) + "[Completed normally]",
854 +                         f.toString());
855 +    }
856 +
857 +    public void testToString_exception() {
858 +        FutureTask<String> f = new FutureTask<String>(
859 +                () -> { throw new ArithmeticException(); });
860 +        f.run();
861 +        assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
862 +        if (testImplementationDetails)
863 +            assertTrue(f.toString().startsWith(
864 +                               identityString(f) + "[Completed exceptionally: "));
865 +    }
866 +
867 +    public void testToString_cancelled() {
868 +        for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
869 +            FutureTask<String> f = new FutureTask<String>(() -> "");
870 +            assertTrue(f.cancel(mayInterruptIfRunning));
871 +            assertTrue(f.toString().matches(".*\\[.*Cancelled.*\\]"));
872 +            if (testImplementationDetails)
873 +                assertEquals(identityString(f) + "[Cancelled]",
874 +                             f.toString());
875 +        }
876 +    }
877 +
878   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines