ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ScheduledExecutorSubclassTest.java
(Generate patch)

Comparing jsr166/src/test/tck/ScheduledExecutorSubclassTest.java (file contents):
Revision 1.64 by jsr166, Wed Jan 4 06:09:58 2017 UTC vs.
Revision 1.67 by jsr166, Mon May 29 19:15:02 2017 UTC

# Line 25 | Line 25 | import java.util.concurrent.RunnableSche
25   import java.util.concurrent.ScheduledFuture;
26   import java.util.concurrent.ScheduledThreadPoolExecutor;
27   import java.util.concurrent.ThreadFactory;
28 + import java.util.concurrent.ThreadLocalRandom;
29   import java.util.concurrent.ThreadPoolExecutor;
30   import java.util.concurrent.TimeoutException;
31   import java.util.concurrent.TimeUnit;
32   import java.util.concurrent.atomic.AtomicBoolean;
33   import java.util.concurrent.atomic.AtomicInteger;
34   import java.util.concurrent.atomic.AtomicLong;
35 + import java.util.stream.Stream;
36  
37   import junit.framework.Test;
38   import junit.framework.TestSuite;
# Line 295 | Line 297 | public class ScheduledExecutorSubclassTe
297          final CustomExecutor p = new CustomExecutor(1);
298          try (PoolCleaner cleaner = cleaner(p)) {
299              try {
300 <                TrackedCallable callable = null;
301 <                Future f = p.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
300 >                Future f = p.schedule((Callable)null,
301 >                                      randomTimeout(), randomTimeUnit());
302                  shouldThrow();
303              } catch (NullPointerException success) {}
304          }
# Line 418 | Line 420 | public class ScheduledExecutorSubclassTe
420                  public void realRun() throws InterruptedException {
421                      threadStarted.countDown();
422                      assertEquals(0, p.getCompletedTaskCount());
423 <                    threadProceed.await();
423 >                    await(threadProceed);
424                      threadDone.countDown();
425                  }});
426              await(threadStarted);
427              assertEquals(0, p.getCompletedTaskCount());
428              threadProceed.countDown();
429 <            threadDone.await();
429 >            await(threadDone);
430              long startTime = System.nanoTime();
431              while (p.getCompletedTaskCount() != 1) {
432                  if (millisElapsedSince(startTime) > LONG_DELAY_MS)
# Line 786 | Line 788 | public class ScheduledExecutorSubclassTe
788       * - setContinueExistingPeriodicTasksAfterShutdownPolicy
789       */
790      public void testShutdown_cancellation() throws Exception {
791 <        Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE };
790 <        for (Boolean policy : allBooleans)
791 <    {
792 <        final int poolSize = 2;
791 >        final int poolSize = 4;
792          final CustomExecutor p = new CustomExecutor(poolSize);
793 <        final boolean effectiveDelayedPolicy = (policy != Boolean.FALSE);
794 <        final boolean effectivePeriodicPolicy = (policy == Boolean.TRUE);
795 <        final boolean effectiveRemovePolicy = (policy == Boolean.TRUE);
796 <        if (policy != null) {
797 <            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(policy);
798 <            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(policy);
799 <            p.setRemoveOnCancelPolicy(policy);
800 <        }
793 >        final BlockingQueue<Runnable> q = p.getQueue();
794 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
795 >        final long delay = rnd.nextInt(2);
796 >        final int rounds = rnd.nextInt(1, 3);
797 >        final boolean effectiveDelayedPolicy;
798 >        final boolean effectivePeriodicPolicy;
799 >        final boolean effectiveRemovePolicy;
800 >
801 >        if (rnd.nextBoolean())
802 >            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(
803 >                effectiveDelayedPolicy = rnd.nextBoolean());
804 >        else
805 >            effectiveDelayedPolicy = true;
806          assertEquals(effectiveDelayedPolicy,
807                       p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
808 +
809 +        if (rnd.nextBoolean())
810 +            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(
811 +                effectivePeriodicPolicy = rnd.nextBoolean());
812 +        else
813 +            effectivePeriodicPolicy = false;
814          assertEquals(effectivePeriodicPolicy,
815                       p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
816 +
817 +        if (rnd.nextBoolean())
818 +            p.setRemoveOnCancelPolicy(
819 +                effectiveRemovePolicy = rnd.nextBoolean());
820 +        else
821 +            effectiveRemovePolicy = false;
822          assertEquals(effectiveRemovePolicy,
823                       p.getRemoveOnCancelPolicy());
824 <        // Strategy: Wedge the pool with poolSize "blocker" threads
824 >
825 >        final boolean periodicTasksContinue = effectivePeriodicPolicy && rnd.nextBoolean();
826 >
827 >        // Strategy: Wedge the pool with one wave of "blocker" tasks,
828 >        // then add a second wave that waits in the queue until unblocked.
829          final AtomicInteger ran = new AtomicInteger(0);
830          final CountDownLatch poolBlocked = new CountDownLatch(poolSize);
831          final CountDownLatch unblock = new CountDownLatch(1);
832 <        final CountDownLatch periodicLatch1 = new CountDownLatch(2);
813 <        final CountDownLatch periodicLatch2 = new CountDownLatch(2);
814 <        Runnable task = new CheckedRunnable() { public void realRun()
815 <                                                    throws InterruptedException {
816 <            poolBlocked.countDown();
817 <            assertTrue(unblock.await(LONG_DELAY_MS, MILLISECONDS));
818 <            ran.getAndIncrement();
819 <        }};
820 <        List<Future<?>> blockers = new ArrayList<>();
821 <        List<Future<?>> periodics = new ArrayList<>();
822 <        List<Future<?>> delayeds = new ArrayList<>();
823 <        for (int i = 0; i < poolSize; i++)
824 <            blockers.add(p.submit(task));
825 <        assertTrue(poolBlocked.await(LONG_DELAY_MS, MILLISECONDS));
826 <
827 <        periodics.add(p.scheduleAtFixedRate(countDowner(periodicLatch1),
828 <                                            1, 1, MILLISECONDS));
829 <        periodics.add(p.scheduleWithFixedDelay(countDowner(periodicLatch2),
830 <                                               1, 1, MILLISECONDS));
831 <        delayeds.add(p.schedule(task, 1, MILLISECONDS));
832 >        final RuntimeException exception = new RuntimeException();
833  
834 <        assertTrue(p.getQueue().containsAll(periodics));
835 <        assertTrue(p.getQueue().containsAll(delayeds));
836 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
837 <        assertTrue(p.isShutdown());
838 <        assertFalse(p.isTerminated());
839 <        for (Future<?> periodic : periodics) {
840 <            assertTrue(effectivePeriodicPolicy ^ periodic.isCancelled());
840 <            assertTrue(effectivePeriodicPolicy ^ periodic.isDone());
841 <        }
842 <        for (Future<?> delayed : delayeds) {
843 <            assertTrue(effectiveDelayedPolicy ^ delayed.isCancelled());
844 <            assertTrue(effectiveDelayedPolicy ^ delayed.isDone());
845 <        }
846 <        if (testImplementationDetails) {
847 <            assertEquals(effectivePeriodicPolicy,
848 <                         p.getQueue().containsAll(periodics));
849 <            assertEquals(effectiveDelayedPolicy,
850 <                         p.getQueue().containsAll(delayeds));
851 <        }
852 <        // Release all pool threads
853 <        unblock.countDown();
854 <
855 <        for (Future<?> delayed : delayeds) {
856 <            if (effectiveDelayedPolicy) {
857 <                assertNull(delayed.get());
834 >        class Task implements Runnable {
835 >            public void run() {
836 >                try {
837 >                    ran.getAndIncrement();
838 >                    poolBlocked.countDown();
839 >                    await(unblock);
840 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
841              }
842          }
843 <        if (effectivePeriodicPolicy) {
844 <            assertTrue(periodicLatch1.await(LONG_DELAY_MS, MILLISECONDS));
845 <            assertTrue(periodicLatch2.await(LONG_DELAY_MS, MILLISECONDS));
846 <            for (Future<?> periodic : periodics) {
847 <                assertTrue(periodic.cancel(false));
848 <                assertTrue(periodic.isCancelled());
849 <                assertTrue(periodic.isDone());
843 >
844 >        class PeriodicTask extends Task {
845 >            PeriodicTask(int rounds) { this.rounds = rounds; }
846 >            int rounds;
847 >            public void run() {
848 >                if (--rounds == 0) super.run();
849 >                // throw exception to surely terminate this periodic task,
850 >                // but in a separate execution and in a detectable way.
851 >                if (rounds == -1) throw exception;
852              }
853          }
854 +
855 +        Runnable task = new Task();
856 +
857 +        List<Future<?>> immediates = new ArrayList<>();
858 +        List<Future<?>> delayeds   = new ArrayList<>();
859 +        List<Future<?>> periodics  = new ArrayList<>();
860 +
861 +        immediates.add(p.submit(task));
862 +        delayeds.add(p.schedule(task, delay, MILLISECONDS));
863 +        periodics.add(p.scheduleAtFixedRate(
864 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
865 +        periodics.add(p.scheduleWithFixedDelay(
866 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
867 +
868 +        await(poolBlocked);
869 +
870 +        assertEquals(poolSize, ran.get());
871 +        assertEquals(poolSize, p.getActiveCount());
872 +        assertTrue(q.isEmpty());
873 +
874 +        // Add second wave of tasks.
875 +        immediates.add(p.submit(task));
876 +        delayeds.add(p.schedule(task, effectiveDelayedPolicy ? delay : LONG_DELAY_MS, MILLISECONDS));
877 +        periodics.add(p.scheduleAtFixedRate(
878 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
879 +        periodics.add(p.scheduleWithFixedDelay(
880 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
881 +
882 +        assertEquals(poolSize, q.size());
883 +        assertEquals(poolSize, ran.get());
884 +
885 +        immediates.forEach(
886 +            f -> assertTrue(((ScheduledFuture)f).getDelay(NANOSECONDS) <= 0L));
887 +
888 +        Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream())
889 +            .forEach(f -> assertFalse(f.isDone()));
890 +
891 +        try { p.shutdown(); } catch (SecurityException ok) { return; }
892 +        assertTrue(p.isShutdown());
893 +        assertTrue(p.isTerminating());
894 +        assertFalse(p.isTerminated());
895 +
896 +        if (rnd.nextBoolean())
897 +            assertThrows(
898 +                RejectedExecutionException.class,
899 +                () -> p.submit(task),
900 +                () -> p.schedule(task, 1, SECONDS),
901 +                () -> p.scheduleAtFixedRate(
902 +                    new PeriodicTask(1), 1, 1, SECONDS),
903 +                () -> p.scheduleWithFixedDelay(
904 +                    new PeriodicTask(2), 1, 1, SECONDS));
905 +
906 +        assertTrue(q.contains(immediates.get(1)));
907 +        assertTrue(!effectiveDelayedPolicy
908 +                   ^ q.contains(delayeds.get(1)));
909 +        assertTrue(!effectivePeriodicPolicy
910 +                   ^ q.containsAll(periodics.subList(2, 4)));
911 +
912 +        immediates.forEach(f -> assertFalse(f.isDone()));
913 +
914 +        assertFalse(delayeds.get(0).isDone());
915 +        if (effectiveDelayedPolicy)
916 +            assertFalse(delayeds.get(1).isDone());
917 +        else
918 +            assertTrue(delayeds.get(1).isCancelled());
919 +
920 +        if (effectivePeriodicPolicy)
921 +            periodics.forEach(
922 +                f -> {
923 +                    assertFalse(f.isDone());
924 +                    if (!periodicTasksContinue) {
925 +                        assertTrue(f.cancel(false));
926 +                        assertTrue(f.isCancelled());
927 +                    }
928 +                });
929 +        else {
930 +            periodics.subList(0, 2).forEach(f -> assertFalse(f.isDone()));
931 +            periodics.subList(2, 4).forEach(f -> assertTrue(f.isCancelled()));
932 +        }
933 +
934 +        unblock.countDown();    // Release all pool threads
935 +
936          assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
937 +        assertFalse(p.isTerminating());
938          assertTrue(p.isTerminated());
939 <        assertEquals(2 + (effectiveDelayedPolicy ? 1 : 0), ran.get());
940 <    }}
939 >
940 >        assertTrue(q.isEmpty());
941 >
942 >        Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream())
943 >            .forEach(f -> assertTrue(f.isDone()));
944 >
945 >        for (Future<?> f : immediates) assertNull(f.get());
946 >
947 >        assertNull(delayeds.get(0).get());
948 >        if (effectiveDelayedPolicy)
949 >            assertNull(delayeds.get(1).get());
950 >        else
951 >            assertTrue(delayeds.get(1).isCancelled());
952 >
953 >        if (periodicTasksContinue)
954 >            periodics.forEach(
955 >                f -> {
956 >                    try { f.get(); }
957 >                    catch (ExecutionException success) {
958 >                        assertSame(exception, success.getCause());
959 >                    }
960 >                    catch (Throwable fail) { threadUnexpectedException(fail); }
961 >                });
962 >        else
963 >            periodics.forEach(f -> assertTrue(f.isCancelled()));
964 >
965 >        assertEquals(poolSize + 1
966 >                     + (effectiveDelayedPolicy ? 1 : 0)
967 >                     + (periodicTasksContinue ? 2 : 0),
968 >                     ran.get());
969 >    }
970  
971      /**
972       * completed submit of callable returns result

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines