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.80 by jsr166, Mon Feb 22 23:16:06 2016 UTC vs.
Revision 1.90 by jsr166, Tue Mar 28 23:21:24 2017 UTC

# Line 18 | Line 18 | import java.util.concurrent.Callable;
18   import java.util.concurrent.CancellationException;
19   import java.util.concurrent.CountDownLatch;
20   import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.Executors;
21   import java.util.concurrent.ExecutorService;
22   import java.util.concurrent.Future;
23   import java.util.concurrent.RejectedExecutionException;
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 51 | 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 363 | 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 508 | 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() {
514
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          }
522        assertTrue(p.isShutdown());
534      }
535  
536      /**
# Line 735 | Line 746 | public class ScheduledExecutorTest exten
746       * - setContinueExistingPeriodicTasksAfterShutdownPolicy
747       */
748      public void testShutdown_cancellation() throws Exception {
749 <        Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE };
739 <        for (Boolean policy : allBooleans)
740 <    {
741 <        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 <            assertTrue(unblock.await(LONG_DELAY_MS, MILLISECONDS));
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 <        assertTrue(poolBlocked.await(LONG_DELAY_MS, MILLISECONDS));
803 <
804 <        periodics.add(p.scheduleAtFixedRate(countDowner(periodicLatch1),
805 <                                            1, 1, MILLISECONDS));
806 <        periodics.add(p.scheduleWithFixedDelay(countDowner(periodicLatch2),
807 <                                               1, 1, MILLISECONDS));
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 >        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 +        assertTrue(q.isEmpty());
831 +
832 +        // Add second wave of tasks.
833 +        immediates.add(p.submit(task));
834 +        long delay_ms = effectiveDelayedPolicy ? 1 : LONG_DELAY_MS;
835 +        delayeds.add(p.schedule(task, delay_ms, MILLISECONDS));
836 +        for (int rounds : new int[] { 1, 2 }) {
837 +            periodics.add(p.scheduleAtFixedRate(
838 +                              new PeriodicTask(rounds), 1, 1, MILLISECONDS));
839 +            periodics.add(p.scheduleWithFixedDelay(
840 +                              new PeriodicTask(rounds), 1, 1, MILLISECONDS));
841 +        }
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  
783        assertTrue(p.getQueue().containsAll(periodics));
784        assertTrue(p.getQueue().containsAll(delayeds));
852          try { p.shutdown(); } catch (SecurityException ok) { return; }
853          assertTrue(p.isShutdown());
854 +        assertTrue(p.isTerminating());
855          assertFalse(p.isTerminated());
856 <        for (Future<?> periodic : periodics) {
857 <            assertTrue(effectivePeriodicPolicy ^ periodic.isCancelled());
858 <            assertTrue(effectivePeriodicPolicy ^ periodic.isDone());
859 <        }
860 <        for (Future<?> delayed : delayeds) {
861 <            assertTrue(effectiveDelayedPolicy ^ delayed.isCancelled());
862 <            assertTrue(effectiveDelayedPolicy ^ delayed.isDone());
863 <        }
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(4, 8)));
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 (testImplementationDetails) {
882 <            assertEquals(effectivePeriodicPolicy,
883 <                         p.getQueue().containsAll(periodics));
884 <            assertEquals(effectiveDelayedPolicy,
885 <                         p.getQueue().containsAll(delayeds));
886 <        }
887 <        // Release all pool threads
888 <        unblock.countDown();
889 <
890 <        for (Future<?> delayed : delayeds) {
891 <            if (effectiveDelayedPolicy) {
807 <                assertNull(delayed.get());
808 <            }
809 <        }
810 <        if (effectivePeriodicPolicy) {
811 <            assertTrue(periodicLatch1.await(LONG_DELAY_MS, MILLISECONDS));
812 <            assertTrue(periodicLatch2.await(LONG_DELAY_MS, MILLISECONDS));
813 <            for (Future<?> periodic : periodics) {
814 <                assertTrue(periodic.cancel(false));
815 <                assertTrue(periodic.isCancelled());
816 <                assertTrue(periodic.isDone());
882 >            if (effectivePeriodicPolicy)
883 >                periodics.forEach(
884 >                    f -> {
885 >                        assertFalse(f.isDone());
886 >                        if (!periodicTasksContinue)
887 >                            assertTrue(f.cancel(false));
888 >                    });
889 >            else {
890 >                periodics.subList(0, 4).forEach(f -> assertFalse(f.isDone()));
891 >                periodics.subList(4, 8).forEach(f -> assertTrue(f.isCancelled()));
892              }
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 ? 4 : 0),
929 >                     ran.get());
930 >    }
931  
932      /**
933       * completed submit of callable returns result
# Line 890 | Line 998 | public class ScheduledExecutorTest exten
998          CountDownLatch latch = new CountDownLatch(1);
999          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1000          try (PoolCleaner cleaner = cleaner(e)) {
1001 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1001 >            List<Callable<String>> l = new ArrayList<>();
1002              l.add(latchAwaitingStringTask(latch));
1003              l.add(null);
1004              try {
# Line 907 | Line 1015 | public class ScheduledExecutorTest exten
1015      public void testInvokeAny4() throws Exception {
1016          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1017          try (PoolCleaner cleaner = cleaner(e)) {
1018 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1018 >            List<Callable<String>> l = new ArrayList<>();
1019              l.add(new NPETask());
1020              try {
1021                  e.invokeAny(l);
# Line 924 | Line 1032 | public class ScheduledExecutorTest exten
1032      public void testInvokeAny5() throws Exception {
1033          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1034          try (PoolCleaner cleaner = cleaner(e)) {
1035 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1035 >            List<Callable<String>> l = new ArrayList<>();
1036              l.add(new StringTask());
1037              l.add(new StringTask());
1038              String result = e.invokeAny(l);
# Line 962 | Line 1070 | public class ScheduledExecutorTest exten
1070      public void testInvokeAll3() throws Exception {
1071          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1072          try (PoolCleaner cleaner = cleaner(e)) {
1073 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1073 >            List<Callable<String>> l = new ArrayList<>();
1074              l.add(new StringTask());
1075              l.add(null);
1076              try {
# Line 978 | Line 1086 | public class ScheduledExecutorTest exten
1086      public void testInvokeAll4() throws Exception {
1087          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1088          try (PoolCleaner cleaner = cleaner(e)) {
1089 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1089 >            List<Callable<String>> l = new ArrayList<>();
1090              l.add(new NPETask());
1091              List<Future<String>> futures = e.invokeAll(l);
1092              assertEquals(1, futures.size());
# Line 997 | Line 1105 | public class ScheduledExecutorTest exten
1105      public void testInvokeAll5() throws Exception {
1106          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1107          try (PoolCleaner cleaner = cleaner(e)) {
1108 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1108 >            List<Callable<String>> l = new ArrayList<>();
1109              l.add(new StringTask());
1110              l.add(new StringTask());
1111              List<Future<String>> futures = e.invokeAll(l);
# Line 1026 | Line 1134 | public class ScheduledExecutorTest exten
1134      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1135          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1136          try (PoolCleaner cleaner = cleaner(e)) {
1137 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1137 >            List<Callable<String>> l = new ArrayList<>();
1138              l.add(new StringTask());
1139              try {
1140                  e.invokeAny(l, MEDIUM_DELAY_MS, null);
# Line 1055 | Line 1163 | public class ScheduledExecutorTest exten
1163          CountDownLatch latch = new CountDownLatch(1);
1164          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1165          try (PoolCleaner cleaner = cleaner(e)) {
1166 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1166 >            List<Callable<String>> l = new ArrayList<>();
1167              l.add(latchAwaitingStringTask(latch));
1168              l.add(null);
1169              try {
# Line 1073 | Line 1181 | public class ScheduledExecutorTest exten
1181          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1182          try (PoolCleaner cleaner = cleaner(e)) {
1183              long startTime = System.nanoTime();
1184 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1184 >            List<Callable<String>> l = new ArrayList<>();
1185              l.add(new NPETask());
1186              try {
1187                  e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1092 | Line 1200 | public class ScheduledExecutorTest exten
1200          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1201          try (PoolCleaner cleaner = cleaner(e)) {
1202              long startTime = System.nanoTime();
1203 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1203 >            List<Callable<String>> l = new ArrayList<>();
1204              l.add(new StringTask());
1205              l.add(new StringTask());
1206              String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1120 | Line 1228 | public class ScheduledExecutorTest exten
1228      public void testTimedInvokeAllNullTimeUnit() throws Exception {
1229          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1230          try (PoolCleaner cleaner = cleaner(e)) {
1231 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1231 >            List<Callable<String>> l = new ArrayList<>();
1232              l.add(new StringTask());
1233              try {
1234                  e.invokeAll(l, MEDIUM_DELAY_MS, null);
# Line 1147 | Line 1255 | public class ScheduledExecutorTest exten
1255      public void testTimedInvokeAll3() throws Exception {
1256          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1257          try (PoolCleaner cleaner = cleaner(e)) {
1258 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1258 >            List<Callable<String>> l = new ArrayList<>();
1259              l.add(new StringTask());
1260              l.add(null);
1261              try {
# Line 1163 | Line 1271 | public class ScheduledExecutorTest exten
1271      public void testTimedInvokeAll4() throws Exception {
1272          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1273          try (PoolCleaner cleaner = cleaner(e)) {
1274 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1274 >            List<Callable<String>> l = new ArrayList<>();
1275              l.add(new NPETask());
1276              List<Future<String>> futures =
1277                  e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1183 | Line 1291 | public class ScheduledExecutorTest exten
1291      public void testTimedInvokeAll5() throws Exception {
1292          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1293          try (PoolCleaner cleaner = cleaner(e)) {
1294 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1294 >            List<Callable<String>> l = new ArrayList<>();
1295              l.add(new StringTask());
1296              l.add(new StringTask());
1297              List<Future<String>> futures =

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines