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.65 by jsr166, Sat Mar 25 21:41:10 2017 UTC vs.
Revision 1.66 by jsr166, Sat Apr 1 16:28:31 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 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);
833 <        final CountDownLatch periodicLatch2 = new CountDownLatch(2);
834 <        Runnable task = new CheckedRunnable() { public void realRun()
835 <                                                    throws InterruptedException {
836 <            poolBlocked.countDown();
837 <            await(unblock);
838 <            ran.getAndIncrement();
839 <        }};
840 <        List<Future<?>> blockers = new ArrayList<>();
841 <        List<Future<?>> periodics = new ArrayList<>();
842 <        List<Future<?>> delayeds = new ArrayList<>();
843 <        for (int i = 0; i < poolSize; i++)
844 <            blockers.add(p.submit(task));
832 >        final RuntimeException exception = new RuntimeException();
833 >
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 >
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 <        periodics.add(p.scheduleAtFixedRate(countDowner(periodicLatch1),
871 <                                            1, 1, MILLISECONDS));
872 <        periodics.add(p.scheduleWithFixedDelay(countDowner(periodicLatch2),
873 <                                               1, 1, MILLISECONDS));
874 <        delayeds.add(p.schedule(task, 1, MILLISECONDS));
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  
833        assertTrue(p.getQueue().containsAll(periodics));
834        assertTrue(p.getQueue().containsAll(delayeds));
891          try { p.shutdown(); } catch (SecurityException ok) { return; }
892          assertTrue(p.isShutdown());
893 +        assertTrue(p.isTerminating());
894          assertFalse(p.isTerminated());
895 <        for (Future<?> periodic : periodics) {
896 <            assertTrue(effectivePeriodicPolicy ^ periodic.isCancelled());
897 <            assertTrue(effectivePeriodicPolicy ^ periodic.isDone());
898 <        }
899 <        for (Future<?> delayed : delayeds) {
900 <            assertTrue(effectiveDelayedPolicy ^ delayed.isCancelled());
901 <            assertTrue(effectiveDelayedPolicy ^ delayed.isDone());
902 <        }
903 <        if (testImplementationDetails) {
904 <            assertEquals(effectivePeriodicPolicy,
905 <                         p.getQueue().containsAll(periodics));
906 <            assertEquals(effectiveDelayedPolicy,
907 <                         p.getQueue().containsAll(delayeds));
908 <        }
909 <        // Release all pool threads
910 <        unblock.countDown();
911 <
912 <        for (Future<?> delayed : delayeds) {
913 <            if (effectiveDelayedPolicy) {
914 <                assertNull(delayed.get());
915 <            }
916 <        }
917 <        if (effectivePeriodicPolicy) {
918 <            await(periodicLatch1);
919 <            await(periodicLatch2);
920 <            for (Future<?> periodic : periodics) {
921 <                assertTrue(periodic.cancel(false));
922 <                assertTrue(periodic.isCancelled());
923 <                assertTrue(periodic.isDone());
924 <            }
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