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

Comparing jsr166/src/test/tck/ScheduledExecutorTest.java (file contents):
Revision 1.86 by jsr166, Sat Mar 25 21:41:10 2017 UTC vs.
Revision 1.91 by jsr166, Wed Mar 29 16:53:20 2017 UTC

# Line 24 | Line 24 | import java.util.concurrent.RejectedExec
24   import java.util.concurrent.ScheduledFuture;
25   import java.util.concurrent.ScheduledThreadPoolExecutor;
26   import java.util.concurrent.ThreadFactory;
27 + import java.util.concurrent.ThreadLocalRandom;
28   import java.util.concurrent.ThreadPoolExecutor;
29   import java.util.concurrent.atomic.AtomicBoolean;
30   import java.util.concurrent.atomic.AtomicInteger;
31   import java.util.concurrent.atomic.AtomicLong;
32 + import java.util.stream.Stream;
33  
34   import junit.framework.Test;
35   import junit.framework.TestSuite;
# Line 744 | Line 746 | public class ScheduledExecutorTest exten
746       * - setContinueExistingPeriodicTasksAfterShutdownPolicy
747       */
748      public void testShutdown_cancellation() throws Exception {
749 <        Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE };
748 <        for (Boolean policy : allBooleans)
749 <    {
750 <        final int poolSize = 2;
749 >        final int poolSize = 6;
750          final ScheduledThreadPoolExecutor p
751              = new ScheduledThreadPoolExecutor(poolSize);
752 <        final boolean effectiveDelayedPolicy = (policy != Boolean.FALSE);
753 <        final boolean effectivePeriodicPolicy = (policy == Boolean.TRUE);
754 <        final boolean effectiveRemovePolicy = (policy == Boolean.TRUE);
755 <        if (policy != null) {
756 <            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(policy);
757 <            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(policy);
758 <            p.setRemoveOnCancelPolicy(policy);
759 <        }
752 >        final BlockingQueue<Runnable> q = p.getQueue();
753 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
754 >        final boolean effectiveDelayedPolicy;
755 >        final boolean effectivePeriodicPolicy;
756 >        final boolean effectiveRemovePolicy;
757 >
758 >        if (rnd.nextBoolean())
759 >            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(
760 >                effectiveDelayedPolicy = rnd.nextBoolean());
761 >        else
762 >            effectiveDelayedPolicy = true;
763          assertEquals(effectiveDelayedPolicy,
764                       p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
765 +
766 +        if (rnd.nextBoolean())
767 +            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(
768 +                effectivePeriodicPolicy = rnd.nextBoolean());
769 +        else
770 +            effectivePeriodicPolicy = false;
771          assertEquals(effectivePeriodicPolicy,
772                       p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
773 +
774 +        if (rnd.nextBoolean())
775 +            p.setRemoveOnCancelPolicy(
776 +                effectiveRemovePolicy = rnd.nextBoolean());
777 +        else
778 +            effectiveRemovePolicy = false;
779          assertEquals(effectiveRemovePolicy,
780                       p.getRemoveOnCancelPolicy());
781 <        // Strategy: Wedge the pool with poolSize "blocker" threads
781 >
782 >        final boolean periodicTasksContinue = effectivePeriodicPolicy && rnd.nextBoolean();
783 >
784 >        // Strategy: Wedge the pool with one wave of "blocker" tasks,
785 >        // then add a second wave that waits in the queue until unblocked.
786          final AtomicInteger ran = new AtomicInteger(0);
787          final CountDownLatch poolBlocked = new CountDownLatch(poolSize);
788          final CountDownLatch unblock = new CountDownLatch(1);
789 <        final CountDownLatch periodicLatch1 = new CountDownLatch(2);
790 <        final CountDownLatch periodicLatch2 = new CountDownLatch(2);
791 <        Runnable task = new CheckedRunnable() { public void realRun()
792 <                                                    throws InterruptedException {
793 <            poolBlocked.countDown();
794 <            await(unblock);
795 <            ran.getAndIncrement();
796 <        }};
797 <        List<Future<?>> blockers = new ArrayList<>();
798 <        List<Future<?>> periodics = new ArrayList<>();
799 <        List<Future<?>> delayeds = new ArrayList<>();
800 <        for (int i = 0; i < poolSize; i++)
801 <            blockers.add(p.submit(task));
802 <        await(poolBlocked);
789 >        final RuntimeException exception = new RuntimeException();
790 >
791 >        class Task implements Runnable {
792 >            public void run() {
793 >                try {
794 >                    ran.getAndIncrement();
795 >                    poolBlocked.countDown();
796 >                    await(unblock);
797 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
798 >            }
799 >        }
800 >
801 >        class PeriodicTask extends Task {
802 >            PeriodicTask(int rounds) { this.rounds = rounds; }
803 >            int rounds;
804 >            public void run() {
805 >                if (--rounds == 0) super.run();
806 >                // throw exception to surely terminate this periodic task,
807 >                // but in a separate execution and in a detectable way.
808 >                if (rounds == -1) throw exception;
809 >            }
810 >        }
811  
812 <        periodics.add(p.scheduleAtFixedRate(countDowner(periodicLatch1),
813 <                                            1, 1, MILLISECONDS));
814 <        periodics.add(p.scheduleWithFixedDelay(countDowner(periodicLatch2),
815 <                                               1, 1, MILLISECONDS));
812 >        Runnable task = new Task();
813 >
814 >        List<Future<?>> immediates = new ArrayList<>();
815 >        List<Future<?>> delayeds   = new ArrayList<>();
816 >        List<Future<?>> periodics  = new ArrayList<>();
817 >
818 >        immediates.add(p.submit(task));
819          delayeds.add(p.schedule(task, 1, MILLISECONDS));
820 +        for (int rounds : new int[] { 1, 2 }) {
821 +            periodics.add(p.scheduleAtFixedRate(
822 +                              new PeriodicTask(rounds), 1, 1, MILLISECONDS));
823 +            periodics.add(p.scheduleWithFixedDelay(
824 +                              new PeriodicTask(rounds), 1, 1, MILLISECONDS));
825 +        }
826 +
827 +        await(poolBlocked);
828 +
829 +        assertEquals(poolSize, ran.get());
830 +        assertEquals(poolSize, p.getActiveCount());
831 +        assertTrue(q.isEmpty());
832 +
833 +        // Add second wave of tasks.
834 +        immediates.add(p.submit(task));
835 +        long delay_ms = effectiveDelayedPolicy ? 1 : LONG_DELAY_MS;
836 +        delayeds.add(p.schedule(task, delay_ms, MILLISECONDS));
837 +        for (int rounds : new int[] { 1, 2 }) {
838 +            periodics.add(p.scheduleAtFixedRate(
839 +                              new PeriodicTask(rounds), 1, 1, MILLISECONDS));
840 +            periodics.add(p.scheduleWithFixedDelay(
841 +                              new PeriodicTask(rounds), 1, 1, MILLISECONDS));
842 +        }
843 +
844 +        assertEquals(poolSize, q.size());
845 +        assertEquals(poolSize, ran.get());
846 +
847 +        immediates.forEach(
848 +            f -> assertTrue(((ScheduledFuture)f).getDelay(NANOSECONDS) <= 0L));
849 +
850 +        Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream())
851 +            .forEach(f -> assertFalse(f.isDone()));
852  
792        assertTrue(p.getQueue().containsAll(periodics));
793        assertTrue(p.getQueue().containsAll(delayeds));
853          try { p.shutdown(); } catch (SecurityException ok) { return; }
854          assertTrue(p.isShutdown());
855 +        assertTrue(p.isTerminating());
856          assertFalse(p.isTerminated());
857 <        for (Future<?> periodic : periodics) {
858 <            assertTrue(effectivePeriodicPolicy ^ periodic.isCancelled());
859 <            assertTrue(effectivePeriodicPolicy ^ periodic.isDone());
860 <        }
861 <        for (Future<?> delayed : delayeds) {
862 <            assertTrue(effectiveDelayedPolicy ^ delayed.isCancelled());
863 <            assertTrue(effectiveDelayedPolicy ^ delayed.isDone());
864 <        }
865 <        if (testImplementationDetails) {
866 <            assertEquals(effectivePeriodicPolicy,
867 <                         p.getQueue().containsAll(periodics));
868 <            assertEquals(effectiveDelayedPolicy,
869 <                         p.getQueue().containsAll(delayeds));
870 <        }
871 <        // Release all pool threads
872 <        unblock.countDown();
873 <
874 <        for (Future<?> delayed : delayeds) {
875 <            if (effectiveDelayedPolicy) {
876 <                assertNull(delayed.get());
877 <            }
878 <        }
879 <        if (effectivePeriodicPolicy) {
880 <            await(periodicLatch1);
881 <            await(periodicLatch2);
882 <            for (Future<?> periodic : periodics) {
883 <                assertTrue(periodic.cancel(false));
884 <                assertTrue(periodic.isCancelled());
885 <                assertTrue(periodic.isDone());
886 <            }
857 >
858 >        if (rnd.nextBoolean())
859 >            assertThrows(
860 >                RejectedExecutionException.class,
861 >                () -> p.submit(task),
862 >                () -> p.schedule(task, 1, SECONDS),
863 >                () -> p.scheduleAtFixedRate(
864 >                    new PeriodicTask(1), 1, 1, SECONDS),
865 >                () -> p.scheduleWithFixedDelay(
866 >                    new PeriodicTask(2), 1, 1, SECONDS));
867 >
868 >        assertTrue(q.contains(immediates.get(1)));
869 >        assertTrue(!effectiveDelayedPolicy
870 >                   ^ q.contains(delayeds.get(1)));
871 >        assertTrue(!effectivePeriodicPolicy
872 >                   ^ q.containsAll(periodics.subList(4, 8)));
873 >
874 >        immediates.forEach(f -> assertFalse(f.isDone()));
875 >
876 >        assertFalse(delayeds.get(0).isDone());
877 >        if (effectiveDelayedPolicy)
878 >            assertFalse(delayeds.get(1).isDone());
879 >        else
880 >            assertTrue(delayeds.get(1).isCancelled());
881 >
882 >        if (effectivePeriodicPolicy)
883 >            periodics.forEach(
884 >                f -> {
885 >                    assertFalse(f.isDone());
886 >                    if (!periodicTasksContinue) {
887 >                        assertTrue(f.cancel(false));
888 >                        assertTrue(f.isCancelled());
889 >                    }
890 >                });
891 >        else {
892 >            periodics.subList(0, 4).forEach(f -> assertFalse(f.isDone()));
893 >            periodics.subList(4, 8).forEach(f -> assertTrue(f.isCancelled()));
894          }
895 <        for (Future<?> blocker : blockers) assertNull(blocker.get());
895 >
896 >        unblock.countDown();    // Release all pool threads
897 >
898          assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
899 +        assertFalse(p.isTerminating());
900          assertTrue(p.isTerminated());
901 <        assertEquals(2 + (effectiveDelayedPolicy ? 1 : 0), ran.get());
902 <    }}
901 >
902 >        assertTrue(q.isEmpty());
903 >
904 >        Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream())
905 >            .forEach(f -> assertTrue(f.isDone()));
906 >
907 >        for (Future<?> f : immediates) assertNull(f.get());
908 >
909 >        assertNull(delayeds.get(0).get());
910 >        if (effectiveDelayedPolicy)
911 >            assertNull(delayeds.get(1).get());
912 >        else
913 >            assertTrue(delayeds.get(1).isCancelled());
914 >
915 >        if (periodicTasksContinue)
916 >            periodics.forEach(
917 >                f -> {
918 >                    try { f.get(); }
919 >                    catch (ExecutionException success) {
920 >                        assertSame(exception, success.getCause());
921 >                    }
922 >                    catch (Throwable fail) { threadUnexpectedException(fail); }
923 >                });
924 >        else
925 >            periodics.forEach(f -> assertTrue(f.isCancelled()));
926 >
927 >        assertEquals(poolSize + 1
928 >                     + (effectiveDelayedPolicy ? 1 : 0)
929 >                     + (periodicTasksContinue ? 4 : 0),
930 >                     ran.get());
931 >    }
932  
933      /**
934       * completed submit of callable returns result

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines