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.83 by jsr166, Wed Jan 4 06:09:58 2017 UTC vs.
Revision 1.94 by jsr166, Mon May 29 22:44:27 2017 UTC

# Line 11 | Line 11 | import static java.util.concurrent.TimeU
11   import static java.util.concurrent.TimeUnit.SECONDS;
12  
13   import java.util.ArrayList;
14 + import java.util.Collection;
15 + import java.util.Collections;
16   import java.util.HashSet;
17   import java.util.List;
18   import java.util.concurrent.BlockingQueue;
# Line 24 | Line 26 | import java.util.concurrent.RejectedExec
26   import java.util.concurrent.ScheduledFuture;
27   import java.util.concurrent.ScheduledThreadPoolExecutor;
28   import java.util.concurrent.ThreadFactory;
29 + import java.util.concurrent.ThreadLocalRandom;
30   import java.util.concurrent.ThreadPoolExecutor;
31   import java.util.concurrent.atomic.AtomicBoolean;
32   import java.util.concurrent.atomic.AtomicInteger;
33   import java.util.concurrent.atomic.AtomicLong;
34 + import java.util.stream.Stream;
35  
36   import junit.framework.Test;
37   import junit.framework.TestSuite;
# Line 50 | Line 54 | public class ScheduledExecutorTest exten
54              final Runnable task = new CheckedRunnable() {
55                  public void realRun() { done.countDown(); }};
56              p.execute(task);
57 <            assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
57 >            await(done);
58          }
59      }
60  
# Line 71 | Line 75 | public class ScheduledExecutorTest exten
75              Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
76              assertSame(Boolean.TRUE, f.get());
77              assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
78 <            assertTrue(done.await(0L, MILLISECONDS));
78 >            assertEquals(0L, done.getCount());
79          }
80      }
81  
# Line 239 | Line 243 | public class ScheduledExecutorTest exten
243          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
244          try (PoolCleaner cleaner = cleaner(p)) {
245              try {
246 <                TrackedCallable callable = null;
247 <                Future f = p.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
246 >                Future f = p.schedule((Callable)null,
247 >                                      randomTimeout(), randomTimeUnit());
248                  shouldThrow();
249              } catch (NullPointerException success) {}
250          }
# Line 255 | Line 259 | public class ScheduledExecutorTest exten
259              try {
260                  p.shutdown();
261                  p.schedule(new NoOpRunnable(),
262 <                           MEDIUM_DELAY_MS, MILLISECONDS);
262 >                           randomTimeout(), randomTimeUnit());
263                  shouldThrow();
264              } catch (RejectedExecutionException success) {
265              } catch (SecurityException ok) {}
# Line 271 | Line 275 | public class ScheduledExecutorTest exten
275              try {
276                  p.shutdown();
277                  p.schedule(new NoOpCallable(),
278 <                           MEDIUM_DELAY_MS, MILLISECONDS);
278 >                           randomTimeout(), randomTimeUnit());
279                  shouldThrow();
280              } catch (RejectedExecutionException success) {
281              } catch (SecurityException ok) {}
# Line 287 | Line 291 | public class ScheduledExecutorTest exten
291              try {
292                  p.shutdown();
293                  p.schedule(new NoOpCallable(),
294 <                           MEDIUM_DELAY_MS, MILLISECONDS);
294 >                           randomTimeout(), randomTimeUnit());
295                  shouldThrow();
296              } catch (RejectedExecutionException success) {
297              } catch (SecurityException ok) {}
# Line 362 | Line 366 | public class ScheduledExecutorTest exten
366                  public void realRun() throws InterruptedException {
367                      threadStarted.countDown();
368                      assertEquals(0, p.getCompletedTaskCount());
369 <                    threadProceed.await();
369 >                    await(threadProceed);
370                      threadDone.countDown();
371                  }});
372              await(threadStarted);
373              assertEquals(0, p.getCompletedTaskCount());
374              threadProceed.countDown();
375 <            threadDone.await();
375 >            await(threadDone);
376              long startTime = System.nanoTime();
377              while (p.getCompletedTaskCount() != 1) {
378                  if (millisElapsedSince(startTime) > LONG_DELAY_MS)
# Line 507 | Line 511 | public class ScheduledExecutorTest exten
511      }
512  
513      /**
514 +     * The default rejected execution handler is AbortPolicy.
515 +     */
516 +    public void testDefaultRejectedExecutionHandler() {
517 +        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
518 +        try (PoolCleaner cleaner = cleaner(p)) {
519 +            assertTrue(p.getRejectedExecutionHandler()
520 +                       instanceof ThreadPoolExecutor.AbortPolicy);
521 +        }
522 +    }
523 +
524 +    /**
525       * isShutdown is false before shutdown, true after
526       */
527      public void testIsShutdown() {
# Line 733 | Line 748 | public class ScheduledExecutorTest exten
748       * - setContinueExistingPeriodicTasksAfterShutdownPolicy
749       */
750      public void testShutdown_cancellation() throws Exception {
751 <        Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE };
737 <        for (Boolean policy : allBooleans)
738 <    {
739 <        final int poolSize = 2;
751 >        final int poolSize = 4;
752          final ScheduledThreadPoolExecutor p
753              = new ScheduledThreadPoolExecutor(poolSize);
754 <        final boolean effectiveDelayedPolicy = (policy != Boolean.FALSE);
755 <        final boolean effectivePeriodicPolicy = (policy == Boolean.TRUE);
756 <        final boolean effectiveRemovePolicy = (policy == Boolean.TRUE);
757 <        if (policy != null) {
758 <            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(policy);
759 <            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(policy);
760 <            p.setRemoveOnCancelPolicy(policy);
761 <        }
754 >        final BlockingQueue<Runnable> q = p.getQueue();
755 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
756 >        final long delay = rnd.nextInt(2);
757 >        final int rounds = rnd.nextInt(1, 3);
758 >        final boolean effectiveDelayedPolicy;
759 >        final boolean effectivePeriodicPolicy;
760 >        final boolean effectiveRemovePolicy;
761 >
762 >        if (rnd.nextBoolean())
763 >            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(
764 >                effectiveDelayedPolicy = rnd.nextBoolean());
765 >        else
766 >            effectiveDelayedPolicy = true;
767          assertEquals(effectiveDelayedPolicy,
768                       p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
769 +
770 +        if (rnd.nextBoolean())
771 +            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(
772 +                effectivePeriodicPolicy = rnd.nextBoolean());
773 +        else
774 +            effectivePeriodicPolicy = false;
775          assertEquals(effectivePeriodicPolicy,
776                       p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
777 +
778 +        if (rnd.nextBoolean())
779 +            p.setRemoveOnCancelPolicy(
780 +                effectiveRemovePolicy = rnd.nextBoolean());
781 +        else
782 +            effectiveRemovePolicy = false;
783          assertEquals(effectiveRemovePolicy,
784                       p.getRemoveOnCancelPolicy());
785 <        // Strategy: Wedge the pool with poolSize "blocker" threads
785 >
786 >        final boolean periodicTasksContinue = effectivePeriodicPolicy && rnd.nextBoolean();
787 >
788 >        // Strategy: Wedge the pool with one wave of "blocker" tasks,
789 >        // then add a second wave that waits in the queue until unblocked.
790          final AtomicInteger ran = new AtomicInteger(0);
791          final CountDownLatch poolBlocked = new CountDownLatch(poolSize);
792          final CountDownLatch unblock = new CountDownLatch(1);
793 <        final CountDownLatch periodicLatch1 = new CountDownLatch(2);
761 <        final CountDownLatch periodicLatch2 = new CountDownLatch(2);
762 <        Runnable task = new CheckedRunnable() { public void realRun()
763 <                                                    throws InterruptedException {
764 <            poolBlocked.countDown();
765 <            assertTrue(unblock.await(LONG_DELAY_MS, MILLISECONDS));
766 <            ran.getAndIncrement();
767 <        }};
768 <        List<Future<?>> blockers = new ArrayList<>();
769 <        List<Future<?>> periodics = new ArrayList<>();
770 <        List<Future<?>> delayeds = new ArrayList<>();
771 <        for (int i = 0; i < poolSize; i++)
772 <            blockers.add(p.submit(task));
773 <        assertTrue(poolBlocked.await(LONG_DELAY_MS, MILLISECONDS));
774 <
775 <        periodics.add(p.scheduleAtFixedRate(countDowner(periodicLatch1),
776 <                                            1, 1, MILLISECONDS));
777 <        periodics.add(p.scheduleWithFixedDelay(countDowner(periodicLatch2),
778 <                                               1, 1, MILLISECONDS));
779 <        delayeds.add(p.schedule(task, 1, MILLISECONDS));
793 >        final RuntimeException exception = new RuntimeException();
794  
795 <        assertTrue(p.getQueue().containsAll(periodics));
796 <        assertTrue(p.getQueue().containsAll(delayeds));
797 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
798 <        assertTrue(p.isShutdown());
799 <        assertFalse(p.isTerminated());
800 <        for (Future<?> periodic : periodics) {
801 <            assertTrue(effectivePeriodicPolicy ^ periodic.isCancelled());
788 <            assertTrue(effectivePeriodicPolicy ^ periodic.isDone());
789 <        }
790 <        for (Future<?> delayed : delayeds) {
791 <            assertTrue(effectiveDelayedPolicy ^ delayed.isCancelled());
792 <            assertTrue(effectiveDelayedPolicy ^ delayed.isDone());
793 <        }
794 <        if (testImplementationDetails) {
795 <            assertEquals(effectivePeriodicPolicy,
796 <                         p.getQueue().containsAll(periodics));
797 <            assertEquals(effectiveDelayedPolicy,
798 <                         p.getQueue().containsAll(delayeds));
799 <        }
800 <        // Release all pool threads
801 <        unblock.countDown();
802 <
803 <        for (Future<?> delayed : delayeds) {
804 <            if (effectiveDelayedPolicy) {
805 <                assertNull(delayed.get());
795 >        class Task implements Runnable {
796 >            public void run() {
797 >                try {
798 >                    ran.getAndIncrement();
799 >                    poolBlocked.countDown();
800 >                    await(unblock);
801 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
802              }
803          }
804 <        if (effectivePeriodicPolicy) {
805 <            assertTrue(periodicLatch1.await(LONG_DELAY_MS, MILLISECONDS));
806 <            assertTrue(periodicLatch2.await(LONG_DELAY_MS, MILLISECONDS));
807 <            for (Future<?> periodic : periodics) {
808 <                assertTrue(periodic.cancel(false));
809 <                assertTrue(periodic.isCancelled());
810 <                assertTrue(periodic.isDone());
804 >
805 >        class PeriodicTask extends Task {
806 >            PeriodicTask(int rounds) { this.rounds = rounds; }
807 >            int rounds;
808 >            public void run() {
809 >                if (--rounds == 0) super.run();
810 >                // throw exception to surely terminate this periodic task,
811 >                // but in a separate execution and in a detectable way.
812 >                if (rounds == -1) throw exception;
813              }
814          }
815 +
816 +        Runnable task = new Task();
817 +
818 +        List<Future<?>> immediates = new ArrayList<>();
819 +        List<Future<?>> delayeds   = new ArrayList<>();
820 +        List<Future<?>> periodics  = new ArrayList<>();
821 +
822 +        immediates.add(p.submit(task));
823 +        delayeds.add(p.schedule(task, delay, MILLISECONDS));
824 +        periodics.add(p.scheduleAtFixedRate(
825 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
826 +        periodics.add(p.scheduleWithFixedDelay(
827 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
828 +
829 +        await(poolBlocked);
830 +
831 +        assertEquals(poolSize, ran.get());
832 +        assertEquals(poolSize, p.getActiveCount());
833 +        assertTrue(q.isEmpty());
834 +
835 +        // Add second wave of tasks.
836 +        immediates.add(p.submit(task));
837 +        delayeds.add(p.schedule(task, effectiveDelayedPolicy ? delay : LONG_DELAY_MS, MILLISECONDS));
838 +        periodics.add(p.scheduleAtFixedRate(
839 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
840 +        periodics.add(p.scheduleWithFixedDelay(
841 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
842 +
843 +        assertEquals(poolSize, q.size());
844 +        assertEquals(poolSize, ran.get());
845 +
846 +        immediates.forEach(
847 +            f -> assertTrue(((ScheduledFuture)f).getDelay(NANOSECONDS) <= 0L));
848 +
849 +        Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream())
850 +            .forEach(f -> assertFalse(f.isDone()));
851 +
852 +        try { p.shutdown(); } catch (SecurityException ok) { return; }
853 +        assertTrue(p.isShutdown());
854 +        assertTrue(p.isTerminating());
855 +        assertFalse(p.isTerminated());
856 +
857 +        if (rnd.nextBoolean())
858 +            assertThrows(
859 +                RejectedExecutionException.class,
860 +                () -> p.submit(task),
861 +                () -> p.schedule(task, 1, SECONDS),
862 +                () -> p.scheduleAtFixedRate(
863 +                    new PeriodicTask(1), 1, 1, SECONDS),
864 +                () -> p.scheduleWithFixedDelay(
865 +                    new PeriodicTask(2), 1, 1, SECONDS));
866 +
867 +        assertTrue(q.contains(immediates.get(1)));
868 +        assertTrue(!effectiveDelayedPolicy
869 +                   ^ q.contains(delayeds.get(1)));
870 +        assertTrue(!effectivePeriodicPolicy
871 +                   ^ q.containsAll(periodics.subList(2, 4)));
872 +
873 +        immediates.forEach(f -> assertFalse(f.isDone()));
874 +
875 +        assertFalse(delayeds.get(0).isDone());
876 +        if (effectiveDelayedPolicy)
877 +            assertFalse(delayeds.get(1).isDone());
878 +        else
879 +            assertTrue(delayeds.get(1).isCancelled());
880 +
881 +        if (effectivePeriodicPolicy)
882 +            periodics.forEach(
883 +                f -> {
884 +                    assertFalse(f.isDone());
885 +                    if (!periodicTasksContinue) {
886 +                        assertTrue(f.cancel(false));
887 +                        assertTrue(f.isCancelled());
888 +                    }
889 +                });
890 +        else {
891 +            periodics.subList(0, 2).forEach(f -> assertFalse(f.isDone()));
892 +            periodics.subList(2, 4).forEach(f -> assertTrue(f.isCancelled()));
893 +        }
894 +
895 +        unblock.countDown();    // Release all pool threads
896 +
897          assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
898 +        assertFalse(p.isTerminating());
899          assertTrue(p.isTerminated());
900 <        assertEquals(2 + (effectiveDelayedPolicy ? 1 : 0), ran.get());
901 <    }}
900 >
901 >        assertTrue(q.isEmpty());
902 >
903 >        Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream())
904 >            .forEach(f -> assertTrue(f.isDone()));
905 >
906 >        for (Future<?> f : immediates) assertNull(f.get());
907 >
908 >        assertNull(delayeds.get(0).get());
909 >        if (effectiveDelayedPolicy)
910 >            assertNull(delayeds.get(1).get());
911 >        else
912 >            assertTrue(delayeds.get(1).isCancelled());
913 >
914 >        if (periodicTasksContinue)
915 >            periodics.forEach(
916 >                f -> {
917 >                    try { f.get(); }
918 >                    catch (ExecutionException success) {
919 >                        assertSame(exception, success.getCause());
920 >                    }
921 >                    catch (Throwable fail) { threadUnexpectedException(fail); }
922 >                });
923 >        else
924 >            periodics.forEach(f -> assertTrue(f.isCancelled()));
925 >
926 >        assertEquals(poolSize + 1
927 >                     + (effectiveDelayedPolicy ? 1 : 0)
928 >                     + (periodicTasksContinue ? 2 : 0),
929 >                     ran.get());
930 >    }
931  
932      /**
933       * completed submit of callable returns result
# Line 856 | Line 966 | public class ScheduledExecutorTest exten
966      }
967  
968      /**
969 <     * invokeAny(null) throws NPE
969 >     * invokeAny(null) throws NullPointerException
970       */
971      public void testInvokeAny1() throws Exception {
972          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
# Line 869 | Line 979 | public class ScheduledExecutorTest exten
979      }
980  
981      /**
982 <     * invokeAny(empty collection) throws IAE
982 >     * invokeAny(empty collection) throws IllegalArgumentException
983       */
984      public void testInvokeAny2() throws Exception {
985          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
# Line 882 | Line 992 | public class ScheduledExecutorTest exten
992      }
993  
994      /**
995 <     * invokeAny(c) throws NPE if c has null elements
995 >     * invokeAny(c) throws NullPointerException if c has null elements
996       */
997      public void testInvokeAny3() throws Exception {
998          CountDownLatch latch = new CountDownLatch(1);
# Line 944 | Line 1054 | public class ScheduledExecutorTest exten
1054      }
1055  
1056      /**
1057 <     * invokeAll(empty collection) returns empty collection
1057 >     * invokeAll(empty collection) returns empty list
1058       */
1059      public void testInvokeAll2() throws Exception {
1060          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1061 +        final Collection<Callable<String>> emptyCollection
1062 +            = Collections.emptyList();
1063          try (PoolCleaner cleaner = cleaner(e)) {
1064 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
1064 >            List<Future<String>> r = e.invokeAll(emptyCollection);
1065              assertTrue(r.isEmpty());
1066          }
1067      }
# Line 1012 | Line 1124 | public class ScheduledExecutorTest exten
1124          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1125          try (PoolCleaner cleaner = cleaner(e)) {
1126              try {
1127 <                e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1127 >                e.invokeAny(null, randomTimeout(), randomTimeUnit());
1128                  shouldThrow();
1129              } catch (NullPointerException success) {}
1130          }
1131      }
1132  
1133      /**
1134 <     * timed invokeAny(,,null) throws NPE
1134 >     * timed invokeAny(,,null) throws NullPointerException
1135       */
1136      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1137          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
# Line 1027 | Line 1139 | public class ScheduledExecutorTest exten
1139              List<Callable<String>> l = new ArrayList<>();
1140              l.add(new StringTask());
1141              try {
1142 <                e.invokeAny(l, MEDIUM_DELAY_MS, null);
1142 >                e.invokeAny(l, randomTimeout(), null);
1143                  shouldThrow();
1144              } catch (NullPointerException success) {}
1145          }
1146      }
1147  
1148      /**
1149 <     * timed invokeAny(empty collection) throws IAE
1149 >     * timed invokeAny(empty collection) throws IllegalArgumentException
1150       */
1151      public void testTimedInvokeAny2() throws Exception {
1152          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1153 +        final Collection<Callable<String>> emptyCollection
1154 +            = Collections.emptyList();
1155          try (PoolCleaner cleaner = cleaner(e)) {
1156              try {
1157 <                e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1157 >                e.invokeAny(emptyCollection, randomTimeout(), randomTimeUnit());
1158                  shouldThrow();
1159              } catch (IllegalArgumentException success) {}
1160          }
# Line 1057 | Line 1171 | public class ScheduledExecutorTest exten
1171              l.add(latchAwaitingStringTask(latch));
1172              l.add(null);
1173              try {
1174 <                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1174 >                e.invokeAny(l, randomTimeout(), randomTimeUnit());
1175                  shouldThrow();
1176              } catch (NullPointerException success) {}
1177              latch.countDown();
# Line 1106 | Line 1220 | public class ScheduledExecutorTest exten
1220          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1221          try (PoolCleaner cleaner = cleaner(e)) {
1222              try {
1223 <                e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1223 >                e.invokeAll(null, randomTimeout(), randomTimeUnit());
1224                  shouldThrow();
1225              } catch (NullPointerException success) {}
1226          }
# Line 1121 | Line 1235 | public class ScheduledExecutorTest exten
1235              List<Callable<String>> l = new ArrayList<>();
1236              l.add(new StringTask());
1237              try {
1238 <                e.invokeAll(l, MEDIUM_DELAY_MS, null);
1238 >                e.invokeAll(l, randomTimeout(), null);
1239                  shouldThrow();
1240              } catch (NullPointerException success) {}
1241          }
1242      }
1243  
1244      /**
1245 <     * timed invokeAll(empty collection) returns empty collection
1245 >     * timed invokeAll(empty collection) returns empty list
1246       */
1247      public void testTimedInvokeAll2() throws Exception {
1248          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1249 +        final Collection<Callable<String>> emptyCollection
1250 +            = Collections.emptyList();
1251          try (PoolCleaner cleaner = cleaner(e)) {
1252 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(),
1253 <                                                 MEDIUM_DELAY_MS, MILLISECONDS);
1252 >            List<Future<String>> r =
1253 >                e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit());
1254              assertTrue(r.isEmpty());
1255          }
1256      }
# Line 1149 | Line 1265 | public class ScheduledExecutorTest exten
1265              l.add(new StringTask());
1266              l.add(null);
1267              try {
1268 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1268 >                e.invokeAll(l, randomTimeout(), randomTimeUnit());
1269                  shouldThrow();
1270              } catch (NullPointerException success) {}
1271          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines