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.61 by jsr166, Mon Feb 22 23:16:06 2016 UTC vs.
Revision 1.66 by jsr166, Sat Apr 1 16:28:31 2017 UTC

# Line 17 | Line 17 | import java.util.concurrent.Cancellation
17   import java.util.concurrent.CountDownLatch;
18   import java.util.concurrent.Delayed;
19   import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.Executors;
20   import java.util.concurrent.ExecutorService;
21   import java.util.concurrent.Future;
22   import java.util.concurrent.RejectedExecutionException;
# Line 26 | 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 45 | Line 46 | public class ScheduledExecutorSubclassTe
46      }
47  
48      static class CustomTask<V> implements RunnableScheduledFuture<V> {
49 <        RunnableScheduledFuture<V> task;
49 >        private final RunnableScheduledFuture<V> task;
50          volatile boolean ran;
51 <        CustomTask(RunnableScheduledFuture<V> t) { task = t; }
51 >        CustomTask(RunnableScheduledFuture<V> task) { this.task = task; }
52          public boolean isPeriodic() { return task.isPeriodic(); }
53          public void run() {
54              ran = true;
# Line 419 | Line 420 | public class ScheduledExecutorSubclassTe
420                  public void realRun() throws InterruptedException {
421                      threadStarted.countDown();
422                      assertEquals(0, p.getCompletedTaskCount());
423 <                    threadProceed.await();
423 >                    await(threadProceed);
424                      threadDone.countDown();
425                  }});
426              await(threadStarted);
427              assertEquals(0, p.getCompletedTaskCount());
428              threadProceed.countDown();
429 <            threadDone.await();
429 >            await(threadDone);
430              long startTime = System.nanoTime();
431              while (p.getCompletedTaskCount() != 1) {
432                  if (millisElapsedSince(startTime) > LONG_DELAY_MS)
# Line 787 | Line 788 | public class ScheduledExecutorSubclassTe
788       * - setContinueExistingPeriodicTasksAfterShutdownPolicy
789       */
790      public void testShutdown_cancellation() throws Exception {
791 <        Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE };
791 <        for (Boolean policy : allBooleans)
792 <    {
793 <        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);
814 <        final CountDownLatch periodicLatch2 = new CountDownLatch(2);
815 <        Runnable task = new CheckedRunnable() { public void realRun()
816 <                                                    throws InterruptedException {
817 <            poolBlocked.countDown();
818 <            assertTrue(unblock.await(LONG_DELAY_MS, MILLISECONDS));
819 <            ran.getAndIncrement();
820 <        }};
821 <        List<Future<?>> blockers = new ArrayList<>();
822 <        List<Future<?>> periodics = new ArrayList<>();
823 <        List<Future<?>> delayeds = new ArrayList<>();
824 <        for (int i = 0; i < poolSize; i++)
825 <            blockers.add(p.submit(task));
826 <        assertTrue(poolBlocked.await(LONG_DELAY_MS, MILLISECONDS));
827 <
828 <        periodics.add(p.scheduleAtFixedRate(countDowner(periodicLatch1),
829 <                                            1, 1, MILLISECONDS));
830 <        periodics.add(p.scheduleWithFixedDelay(countDowner(periodicLatch2),
831 <                                               1, 1, MILLISECONDS));
832 <        delayeds.add(p.schedule(task, 1, MILLISECONDS));
832 >        final RuntimeException exception = new RuntimeException();
833  
834 <        assertTrue(p.getQueue().containsAll(periodics));
835 <        assertTrue(p.getQueue().containsAll(delayeds));
836 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
837 <        assertTrue(p.isShutdown());
838 <        assertFalse(p.isTerminated());
839 <        for (Future<?> periodic : periodics) {
840 <            assertTrue(effectivePeriodicPolicy ^ periodic.isCancelled());
841 <            assertTrue(effectivePeriodicPolicy ^ periodic.isDone());
842 <        }
843 <        for (Future<?> delayed : delayeds) {
844 <            assertTrue(effectiveDelayedPolicy ^ delayed.isCancelled());
845 <            assertTrue(effectiveDelayedPolicy ^ delayed.isDone());
846 <        }
847 <        if (testImplementationDetails) {
848 <            assertEquals(effectivePeriodicPolicy,
849 <                         p.getQueue().containsAll(periodics));
850 <            assertEquals(effectiveDelayedPolicy,
851 <                         p.getQueue().containsAll(delayeds));
852 <        }
853 <        // Release all pool threads
854 <        unblock.countDown();
855 <
856 <        for (Future<?> delayed : delayeds) {
857 <            if (effectiveDelayedPolicy) {
858 <                assertNull(delayed.get());
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 <        if (effectivePeriodicPolicy) {
844 <            assertTrue(periodicLatch1.await(LONG_DELAY_MS, MILLISECONDS));
845 <            assertTrue(periodicLatch2.await(LONG_DELAY_MS, MILLISECONDS));
846 <            for (Future<?> periodic : periodics) {
847 <                assertTrue(periodic.cancel(false));
848 <                assertTrue(periodic.isCancelled());
849 <                assertTrue(periodic.isDone());
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 +        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 +
891 +        try { p.shutdown(); } catch (SecurityException ok) { return; }
892 +        assertTrue(p.isShutdown());
893 +        assertTrue(p.isTerminating());
894 +        assertFalse(p.isTerminated());
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
# Line 941 | Line 1037 | public class ScheduledExecutorSubclassTe
1037          final CountDownLatch latch = new CountDownLatch(1);
1038          final ExecutorService e = new CustomExecutor(2);
1039          try (PoolCleaner cleaner = cleaner(e)) {
1040 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1040 >            List<Callable<String>> l = new ArrayList<>();
1041              l.add(latchAwaitingStringTask(latch));
1042              l.add(null);
1043              try {
# Line 958 | Line 1054 | public class ScheduledExecutorSubclassTe
1054      public void testInvokeAny4() throws Exception {
1055          final ExecutorService e = new CustomExecutor(2);
1056          try (PoolCleaner cleaner = cleaner(e)) {
1057 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1057 >            List<Callable<String>> l = new ArrayList<>();
1058              l.add(new NPETask());
1059              try {
1060                  e.invokeAny(l);
# Line 975 | Line 1071 | public class ScheduledExecutorSubclassTe
1071      public void testInvokeAny5() throws Exception {
1072          final ExecutorService e = new CustomExecutor(2);
1073          try (PoolCleaner cleaner = cleaner(e)) {
1074 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1074 >            List<Callable<String>> l = new ArrayList<>();
1075              l.add(new StringTask());
1076              l.add(new StringTask());
1077              String result = e.invokeAny(l);
# Line 1013 | Line 1109 | public class ScheduledExecutorSubclassTe
1109      public void testInvokeAll3() throws Exception {
1110          final ExecutorService e = new CustomExecutor(2);
1111          try (PoolCleaner cleaner = cleaner(e)) {
1112 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1112 >            List<Callable<String>> l = new ArrayList<>();
1113              l.add(new StringTask());
1114              l.add(null);
1115              try {
# Line 1029 | Line 1125 | public class ScheduledExecutorSubclassTe
1125      public void testInvokeAll4() throws Exception {
1126          final ExecutorService e = new CustomExecutor(2);
1127          try (PoolCleaner cleaner = cleaner(e)) {
1128 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1128 >            List<Callable<String>> l = new ArrayList<>();
1129              l.add(new NPETask());
1130              List<Future<String>> futures = e.invokeAll(l);
1131              assertEquals(1, futures.size());
# Line 1048 | Line 1144 | public class ScheduledExecutorSubclassTe
1144      public void testInvokeAll5() throws Exception {
1145          final ExecutorService e = new CustomExecutor(2);
1146          try (PoolCleaner cleaner = cleaner(e)) {
1147 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1147 >            List<Callable<String>> l = new ArrayList<>();
1148              l.add(new StringTask());
1149              l.add(new StringTask());
1150              List<Future<String>> futures = e.invokeAll(l);
# Line 1077 | Line 1173 | public class ScheduledExecutorSubclassTe
1173      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1174          final ExecutorService e = new CustomExecutor(2);
1175          try (PoolCleaner cleaner = cleaner(e)) {
1176 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1176 >            List<Callable<String>> l = new ArrayList<>();
1177              l.add(new StringTask());
1178              try {
1179                  e.invokeAny(l, MEDIUM_DELAY_MS, null);
# Line 1106 | Line 1202 | public class ScheduledExecutorSubclassTe
1202          CountDownLatch latch = new CountDownLatch(1);
1203          final ExecutorService e = new CustomExecutor(2);
1204          try (PoolCleaner cleaner = cleaner(e)) {
1205 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1205 >            List<Callable<String>> l = new ArrayList<>();
1206              l.add(latchAwaitingStringTask(latch));
1207              l.add(null);
1208              try {
# Line 1124 | Line 1220 | public class ScheduledExecutorSubclassTe
1220          final ExecutorService e = new CustomExecutor(2);
1221          try (PoolCleaner cleaner = cleaner(e)) {
1222              long startTime = System.nanoTime();
1223 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1223 >            List<Callable<String>> l = new ArrayList<>();
1224              l.add(new NPETask());
1225              try {
1226                  e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1143 | Line 1239 | public class ScheduledExecutorSubclassTe
1239          final ExecutorService e = new CustomExecutor(2);
1240          try (PoolCleaner cleaner = cleaner(e)) {
1241              long startTime = System.nanoTime();
1242 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1242 >            List<Callable<String>> l = new ArrayList<>();
1243              l.add(new StringTask());
1244              l.add(new StringTask());
1245              String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1171 | Line 1267 | public class ScheduledExecutorSubclassTe
1267      public void testTimedInvokeAllNullTimeUnit() throws Exception {
1268          final ExecutorService e = new CustomExecutor(2);
1269          try (PoolCleaner cleaner = cleaner(e)) {
1270 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1270 >            List<Callable<String>> l = new ArrayList<>();
1271              l.add(new StringTask());
1272              try {
1273                  e.invokeAll(l, MEDIUM_DELAY_MS, null);
# Line 1197 | Line 1293 | public class ScheduledExecutorSubclassTe
1293      public void testTimedInvokeAll3() throws Exception {
1294          final ExecutorService e = new CustomExecutor(2);
1295          try (PoolCleaner cleaner = cleaner(e)) {
1296 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1296 >            List<Callable<String>> l = new ArrayList<>();
1297              l.add(new StringTask());
1298              l.add(null);
1299              try {
# Line 1213 | Line 1309 | public class ScheduledExecutorSubclassTe
1309      public void testTimedInvokeAll4() throws Exception {
1310          final ExecutorService e = new CustomExecutor(2);
1311          try (PoolCleaner cleaner = cleaner(e)) {
1312 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1312 >            List<Callable<String>> l = new ArrayList<>();
1313              l.add(new NPETask());
1314              List<Future<String>> futures =
1315                  e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
# Line 1233 | Line 1329 | public class ScheduledExecutorSubclassTe
1329      public void testTimedInvokeAll5() throws Exception {
1330          final ExecutorService e = new CustomExecutor(2);
1331          try (PoolCleaner cleaner = cleaner(e)) {
1332 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1332 >            List<Callable<String>> l = new ArrayList<>();
1333              l.add(new StringTask());
1334              l.add(new StringTask());
1335              List<Future<String>> futures =

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines