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.81 by jsr166, Wed Aug 24 22:22:39 2016 UTC vs.
Revision 1.93 by jsr166, Mon May 29 19:15:03 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 50 | Line 52 | public class ScheduledExecutorTest exten
52              final Runnable task = new CheckedRunnable() {
53                  public void realRun() { done.countDown(); }};
54              p.execute(task);
55 <            assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
55 >            await(done);
56          }
57      }
58  
# Line 71 | Line 73 | public class ScheduledExecutorTest exten
73              Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
74              assertSame(Boolean.TRUE, f.get());
75              assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
76 <            assertTrue(done.await(0L, MILLISECONDS));
76 >            assertEquals(0L, done.getCount());
77          }
78      }
79  
# Line 239 | Line 241 | public class ScheduledExecutorTest exten
241          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
242          try (PoolCleaner cleaner = cleaner(p)) {
243              try {
244 <                TrackedCallable callable = null;
245 <                Future f = p.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
244 >                Future f = p.schedule((Callable)null,
245 >                                      randomTimeout(), randomTimeUnit());
246                  shouldThrow();
247              } catch (NullPointerException success) {}
248          }
# Line 362 | Line 364 | public class ScheduledExecutorTest exten
364                  public void realRun() throws InterruptedException {
365                      threadStarted.countDown();
366                      assertEquals(0, p.getCompletedTaskCount());
367 <                    threadProceed.await();
367 >                    await(threadProceed);
368                      threadDone.countDown();
369                  }});
370              await(threadStarted);
371              assertEquals(0, p.getCompletedTaskCount());
372              threadProceed.countDown();
373 <            threadDone.await();
373 >            await(threadDone);
374              long startTime = System.nanoTime();
375              while (p.getCompletedTaskCount() != 1) {
376                  if (millisElapsedSince(startTime) > LONG_DELAY_MS)
# Line 507 | Line 509 | public class ScheduledExecutorTest exten
509      }
510  
511      /**
512 +     * The default rejected execution handler is AbortPolicy.
513 +     */
514 +    public void testDefaultRejectedExecutionHandler() {
515 +        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
516 +        try (PoolCleaner cleaner = cleaner(p)) {
517 +            assertTrue(p.getRejectedExecutionHandler()
518 +                       instanceof ThreadPoolExecutor.AbortPolicy);
519 +        }
520 +    }
521 +
522 +    /**
523       * isShutdown is false before shutdown, true after
524       */
525      public void testIsShutdown() {
513
526          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
527 <        try {
528 <            assertFalse(p.isShutdown());
529 <        }
530 <        finally {
531 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
527 >        assertFalse(p.isShutdown());
528 >        try (PoolCleaner cleaner = cleaner(p)) {
529 >            try {
530 >                p.shutdown();
531 >                assertTrue(p.isShutdown());
532 >            } catch (SecurityException ok) {}
533          }
521        assertTrue(p.isShutdown());
534      }
535  
536      /**
# Line 734 | Line 746 | public class ScheduledExecutorTest exten
746       * - setContinueExistingPeriodicTasksAfterShutdownPolicy
747       */
748      public void testShutdown_cancellation() throws Exception {
749 <        Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE };
738 <        for (Boolean policy : allBooleans)
739 <    {
740 <        final int poolSize = 2;
749 >        final int poolSize = 4;
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 long delay = rnd.nextInt(2);
755 >        final int rounds = rnd.nextInt(1, 3);
756 >        final boolean effectiveDelayedPolicy;
757 >        final boolean effectivePeriodicPolicy;
758 >        final boolean effectiveRemovePolicy;
759 >
760 >        if (rnd.nextBoolean())
761 >            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(
762 >                effectiveDelayedPolicy = rnd.nextBoolean());
763 >        else
764 >            effectiveDelayedPolicy = true;
765          assertEquals(effectiveDelayedPolicy,
766                       p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
767 +
768 +        if (rnd.nextBoolean())
769 +            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(
770 +                effectivePeriodicPolicy = rnd.nextBoolean());
771 +        else
772 +            effectivePeriodicPolicy = false;
773          assertEquals(effectivePeriodicPolicy,
774                       p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
775 +
776 +        if (rnd.nextBoolean())
777 +            p.setRemoveOnCancelPolicy(
778 +                effectiveRemovePolicy = rnd.nextBoolean());
779 +        else
780 +            effectiveRemovePolicy = false;
781          assertEquals(effectiveRemovePolicy,
782                       p.getRemoveOnCancelPolicy());
783 <        // Strategy: Wedge the pool with poolSize "blocker" threads
783 >
784 >        final boolean periodicTasksContinue = effectivePeriodicPolicy && rnd.nextBoolean();
785 >
786 >        // Strategy: Wedge the pool with one wave of "blocker" tasks,
787 >        // then add a second wave that waits in the queue until unblocked.
788          final AtomicInteger ran = new AtomicInteger(0);
789          final CountDownLatch poolBlocked = new CountDownLatch(poolSize);
790          final CountDownLatch unblock = new CountDownLatch(1);
791 <        final CountDownLatch periodicLatch1 = new CountDownLatch(2);
762 <        final CountDownLatch periodicLatch2 = new CountDownLatch(2);
763 <        Runnable task = new CheckedRunnable() { public void realRun()
764 <                                                    throws InterruptedException {
765 <            poolBlocked.countDown();
766 <            assertTrue(unblock.await(LONG_DELAY_MS, MILLISECONDS));
767 <            ran.getAndIncrement();
768 <        }};
769 <        List<Future<?>> blockers = new ArrayList<>();
770 <        List<Future<?>> periodics = new ArrayList<>();
771 <        List<Future<?>> delayeds = new ArrayList<>();
772 <        for (int i = 0; i < poolSize; i++)
773 <            blockers.add(p.submit(task));
774 <        assertTrue(poolBlocked.await(LONG_DELAY_MS, MILLISECONDS));
775 <
776 <        periodics.add(p.scheduleAtFixedRate(countDowner(periodicLatch1),
777 <                                            1, 1, MILLISECONDS));
778 <        periodics.add(p.scheduleWithFixedDelay(countDowner(periodicLatch2),
779 <                                               1, 1, MILLISECONDS));
780 <        delayeds.add(p.schedule(task, 1, MILLISECONDS));
791 >        final RuntimeException exception = new RuntimeException();
792  
793 <        assertTrue(p.getQueue().containsAll(periodics));
794 <        assertTrue(p.getQueue().containsAll(delayeds));
795 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
796 <        assertTrue(p.isShutdown());
797 <        assertFalse(p.isTerminated());
798 <        for (Future<?> periodic : periodics) {
799 <            assertTrue(effectivePeriodicPolicy ^ periodic.isCancelled());
789 <            assertTrue(effectivePeriodicPolicy ^ periodic.isDone());
790 <        }
791 <        for (Future<?> delayed : delayeds) {
792 <            assertTrue(effectiveDelayedPolicy ^ delayed.isCancelled());
793 <            assertTrue(effectiveDelayedPolicy ^ delayed.isDone());
794 <        }
795 <        if (testImplementationDetails) {
796 <            assertEquals(effectivePeriodicPolicy,
797 <                         p.getQueue().containsAll(periodics));
798 <            assertEquals(effectiveDelayedPolicy,
799 <                         p.getQueue().containsAll(delayeds));
800 <        }
801 <        // Release all pool threads
802 <        unblock.countDown();
803 <
804 <        for (Future<?> delayed : delayeds) {
805 <            if (effectiveDelayedPolicy) {
806 <                assertNull(delayed.get());
793 >        class Task implements Runnable {
794 >            public void run() {
795 >                try {
796 >                    ran.getAndIncrement();
797 >                    poolBlocked.countDown();
798 >                    await(unblock);
799 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
800              }
801          }
802 <        if (effectivePeriodicPolicy) {
803 <            assertTrue(periodicLatch1.await(LONG_DELAY_MS, MILLISECONDS));
804 <            assertTrue(periodicLatch2.await(LONG_DELAY_MS, MILLISECONDS));
805 <            for (Future<?> periodic : periodics) {
806 <                assertTrue(periodic.cancel(false));
807 <                assertTrue(periodic.isCancelled());
808 <                assertTrue(periodic.isDone());
802 >
803 >        class PeriodicTask extends Task {
804 >            PeriodicTask(int rounds) { this.rounds = rounds; }
805 >            int rounds;
806 >            public void run() {
807 >                if (--rounds == 0) super.run();
808 >                // throw exception to surely terminate this periodic task,
809 >                // but in a separate execution and in a detectable way.
810 >                if (rounds == -1) throw exception;
811              }
812          }
813 +
814 +        Runnable task = new Task();
815 +
816 +        List<Future<?>> immediates = new ArrayList<>();
817 +        List<Future<?>> delayeds   = new ArrayList<>();
818 +        List<Future<?>> periodics  = new ArrayList<>();
819 +
820 +        immediates.add(p.submit(task));
821 +        delayeds.add(p.schedule(task, delay, MILLISECONDS));
822 +        periodics.add(p.scheduleAtFixedRate(
823 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
824 +        periodics.add(p.scheduleWithFixedDelay(
825 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
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 +        delayeds.add(p.schedule(task, effectiveDelayedPolicy ? delay : LONG_DELAY_MS, MILLISECONDS));
836 +        periodics.add(p.scheduleAtFixedRate(
837 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
838 +        periodics.add(p.scheduleWithFixedDelay(
839 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
840 +
841 +        assertEquals(poolSize, q.size());
842 +        assertEquals(poolSize, ran.get());
843 +
844 +        immediates.forEach(
845 +            f -> assertTrue(((ScheduledFuture)f).getDelay(NANOSECONDS) <= 0L));
846 +
847 +        Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream())
848 +            .forEach(f -> assertFalse(f.isDone()));
849 +
850 +        try { p.shutdown(); } catch (SecurityException ok) { return; }
851 +        assertTrue(p.isShutdown());
852 +        assertTrue(p.isTerminating());
853 +        assertFalse(p.isTerminated());
854 +
855 +        if (rnd.nextBoolean())
856 +            assertThrows(
857 +                RejectedExecutionException.class,
858 +                () -> p.submit(task),
859 +                () -> p.schedule(task, 1, SECONDS),
860 +                () -> p.scheduleAtFixedRate(
861 +                    new PeriodicTask(1), 1, 1, SECONDS),
862 +                () -> p.scheduleWithFixedDelay(
863 +                    new PeriodicTask(2), 1, 1, SECONDS));
864 +
865 +        assertTrue(q.contains(immediates.get(1)));
866 +        assertTrue(!effectiveDelayedPolicy
867 +                   ^ q.contains(delayeds.get(1)));
868 +        assertTrue(!effectivePeriodicPolicy
869 +                   ^ q.containsAll(periodics.subList(2, 4)));
870 +
871 +        immediates.forEach(f -> assertFalse(f.isDone()));
872 +
873 +        assertFalse(delayeds.get(0).isDone());
874 +        if (effectiveDelayedPolicy)
875 +            assertFalse(delayeds.get(1).isDone());
876 +        else
877 +            assertTrue(delayeds.get(1).isCancelled());
878 +
879 +        if (effectivePeriodicPolicy)
880 +            periodics.forEach(
881 +                f -> {
882 +                    assertFalse(f.isDone());
883 +                    if (!periodicTasksContinue) {
884 +                        assertTrue(f.cancel(false));
885 +                        assertTrue(f.isCancelled());
886 +                    }
887 +                });
888 +        else {
889 +            periodics.subList(0, 2).forEach(f -> assertFalse(f.isDone()));
890 +            periodics.subList(2, 4).forEach(f -> assertTrue(f.isCancelled()));
891 +        }
892 +
893 +        unblock.countDown();    // Release all pool threads
894 +
895          assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
896 +        assertFalse(p.isTerminating());
897          assertTrue(p.isTerminated());
898 <        assertEquals(2 + (effectiveDelayedPolicy ? 1 : 0), ran.get());
899 <    }}
898 >
899 >        assertTrue(q.isEmpty());
900 >
901 >        Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream())
902 >            .forEach(f -> assertTrue(f.isDone()));
903 >
904 >        for (Future<?> f : immediates) assertNull(f.get());
905 >
906 >        assertNull(delayeds.get(0).get());
907 >        if (effectiveDelayedPolicy)
908 >            assertNull(delayeds.get(1).get());
909 >        else
910 >            assertTrue(delayeds.get(1).isCancelled());
911 >
912 >        if (periodicTasksContinue)
913 >            periodics.forEach(
914 >                f -> {
915 >                    try { f.get(); }
916 >                    catch (ExecutionException success) {
917 >                        assertSame(exception, success.getCause());
918 >                    }
919 >                    catch (Throwable fail) { threadUnexpectedException(fail); }
920 >                });
921 >        else
922 >            periodics.forEach(f -> assertTrue(f.isCancelled()));
923 >
924 >        assertEquals(poolSize + 1
925 >                     + (effectiveDelayedPolicy ? 1 : 0)
926 >                     + (periodicTasksContinue ? 2 : 0),
927 >                     ran.get());
928 >    }
929  
930      /**
931       * completed submit of callable returns result
# Line 889 | Line 996 | public class ScheduledExecutorTest exten
996          CountDownLatch latch = new CountDownLatch(1);
997          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
998          try (PoolCleaner cleaner = cleaner(e)) {
999 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
999 >            List<Callable<String>> l = new ArrayList<>();
1000              l.add(latchAwaitingStringTask(latch));
1001              l.add(null);
1002              try {
# Line 906 | Line 1013 | public class ScheduledExecutorTest exten
1013      public void testInvokeAny4() throws Exception {
1014          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1015          try (PoolCleaner cleaner = cleaner(e)) {
1016 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1016 >            List<Callable<String>> l = new ArrayList<>();
1017              l.add(new NPETask());
1018              try {
1019                  e.invokeAny(l);
# Line 923 | Line 1030 | public class ScheduledExecutorTest exten
1030      public void testInvokeAny5() throws Exception {
1031          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1032          try (PoolCleaner cleaner = cleaner(e)) {
1033 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1033 >            List<Callable<String>> l = new ArrayList<>();
1034              l.add(new StringTask());
1035              l.add(new StringTask());
1036              String result = e.invokeAny(l);
# Line 961 | Line 1068 | public class ScheduledExecutorTest exten
1068      public void testInvokeAll3() throws Exception {
1069          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1070          try (PoolCleaner cleaner = cleaner(e)) {
1071 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1071 >            List<Callable<String>> l = new ArrayList<>();
1072              l.add(new StringTask());
1073              l.add(null);
1074              try {
# Line 977 | Line 1084 | public class ScheduledExecutorTest exten
1084      public void testInvokeAll4() throws Exception {
1085          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1086          try (PoolCleaner cleaner = cleaner(e)) {
1087 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1087 >            List<Callable<String>> l = new ArrayList<>();
1088              l.add(new NPETask());
1089              List<Future<String>> futures = e.invokeAll(l);
1090              assertEquals(1, futures.size());
# Line 996 | Line 1103 | public class ScheduledExecutorTest exten
1103      public void testInvokeAll5() throws Exception {
1104          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1105          try (PoolCleaner cleaner = cleaner(e)) {
1106 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1106 >            List<Callable<String>> l = new ArrayList<>();
1107              l.add(new StringTask());
1108              l.add(new StringTask());
1109              List<Future<String>> futures = e.invokeAll(l);
# Line 1025 | Line 1132 | public class ScheduledExecutorTest exten
1132      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1133          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1134          try (PoolCleaner cleaner = cleaner(e)) {
1135 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1135 >            List<Callable<String>> l = new ArrayList<>();
1136              l.add(new StringTask());
1137              try {
1138                  e.invokeAny(l, MEDIUM_DELAY_MS, null);
# Line 1054 | Line 1161 | public class ScheduledExecutorTest exten
1161          CountDownLatch latch = new CountDownLatch(1);
1162          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1163          try (PoolCleaner cleaner = cleaner(e)) {
1164 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1164 >            List<Callable<String>> l = new ArrayList<>();
1165              l.add(latchAwaitingStringTask(latch));
1166              l.add(null);
1167              try {
# Line 1072 | Line 1179 | public class ScheduledExecutorTest exten
1179          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1180          try (PoolCleaner cleaner = cleaner(e)) {
1181              long startTime = System.nanoTime();
1182 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1182 >            List<Callable<String>> l = new ArrayList<>();
1183              l.add(new NPETask());
1184              try {
1185                  e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1091 | Line 1198 | public class ScheduledExecutorTest exten
1198          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1199          try (PoolCleaner cleaner = cleaner(e)) {
1200              long startTime = System.nanoTime();
1201 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1201 >            List<Callable<String>> l = new ArrayList<>();
1202              l.add(new StringTask());
1203              l.add(new StringTask());
1204              String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1119 | Line 1226 | public class ScheduledExecutorTest exten
1226      public void testTimedInvokeAllNullTimeUnit() throws Exception {
1227          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1228          try (PoolCleaner cleaner = cleaner(e)) {
1229 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1229 >            List<Callable<String>> l = new ArrayList<>();
1230              l.add(new StringTask());
1231              try {
1232                  e.invokeAll(l, MEDIUM_DELAY_MS, null);
# Line 1146 | Line 1253 | public class ScheduledExecutorTest exten
1253      public void testTimedInvokeAll3() throws Exception {
1254          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1255          try (PoolCleaner cleaner = cleaner(e)) {
1256 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1256 >            List<Callable<String>> l = new ArrayList<>();
1257              l.add(new StringTask());
1258              l.add(null);
1259              try {
# Line 1162 | Line 1269 | public class ScheduledExecutorTest exten
1269      public void testTimedInvokeAll4() throws Exception {
1270          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1271          try (PoolCleaner cleaner = cleaner(e)) {
1272 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1272 >            List<Callable<String>> l = new ArrayList<>();
1273              l.add(new NPETask());
1274              List<Future<String>> futures =
1275                  e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1182 | Line 1289 | public class ScheduledExecutorTest exten
1289      public void testTimedInvokeAll5() throws Exception {
1290          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1291          try (PoolCleaner cleaner = cleaner(e)) {
1292 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1292 >            List<Callable<String>> l = new ArrayList<>();
1293              l.add(new StringTask());
1294              l.add(new StringTask());
1295              List<Future<String>> futures =

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines