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.76 by jsr166, Thu Oct 8 03:08:37 2015 UTC vs.
Revision 1.88 by jsr166, Sun Mar 26 02:00:39 2017 UTC

# Line 7 | Line 7
7   */
8  
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 + import static java.util.concurrent.TimeUnit.NANOSECONDS;
11   import static java.util.concurrent.TimeUnit.SECONDS;
12  
13   import java.util.ArrayList;
# Line 17 | 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;
20 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  
33   import junit.framework.Test;
34   import junit.framework.TestSuite;
# Line 48 | Line 51 | public class ScheduledExecutorTest exten
51              final Runnable task = new CheckedRunnable() {
52                  public void realRun() { done.countDown(); }};
53              p.execute(task);
54 <            assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
54 >            await(done);
55          }
56      }
57  
# Line 143 | Line 146 | public class ScheduledExecutorTest exten
146      }
147  
148      /**
149 <     * scheduleAtFixedRate executes series of tasks at given rate
149 >     * scheduleAtFixedRate executes series of tasks at given rate.
150 >     * Eventually, it must hold that:
151 >     *   cycles - 1 <= elapsedMillis/delay < cycles
152       */
153      public void testFixedRateSequence() throws InterruptedException {
154          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
155          try (PoolCleaner cleaner = cleaner(p)) {
156              for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
157 <                long startTime = System.nanoTime();
158 <                int cycles = 10;
157 >                final long startTime = System.nanoTime();
158 >                final int cycles = 8;
159                  final CountDownLatch done = new CountDownLatch(cycles);
160 <                Runnable task = new CheckedRunnable() {
160 >                final Runnable task = new CheckedRunnable() {
161                      public void realRun() { done.countDown(); }};
162 <                ScheduledFuture h =
162 >                final ScheduledFuture periodicTask =
163                      p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
164 <                await(done);
165 <                h.cancel(true);
166 <                double normalizedTime =
167 <                    (double) millisElapsedSince(startTime) / delay;
168 <                if (normalizedTime >= cycles - 1 &&
169 <                    normalizedTime <= cycles)
164 >                final int totalDelayMillis = (cycles - 1) * delay;
165 >                await(done, totalDelayMillis + LONG_DELAY_MS);
166 >                periodicTask.cancel(true);
167 >                final long elapsedMillis = millisElapsedSince(startTime);
168 >                assertTrue(elapsedMillis >= totalDelayMillis);
169 >                if (elapsedMillis <= cycles * delay)
170                      return;
171 +                // else retry with longer delay
172              }
173 <            throw new AssertionError("unexpected execution rate");
173 >            fail("unexpected execution rate");
174          }
175      }
176  
177      /**
178 <     * scheduleWithFixedDelay executes series of tasks with given period
178 >     * scheduleWithFixedDelay executes series of tasks with given period.
179 >     * Eventually, it must hold that each task starts at least delay and at
180 >     * most 2 * delay after the termination of the previous task.
181       */
182      public void testFixedDelaySequence() throws InterruptedException {
183          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
184          try (PoolCleaner cleaner = cleaner(p)) {
185              for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
186 <                long startTime = System.nanoTime();
187 <                int cycles = 10;
186 >                final long startTime = System.nanoTime();
187 >                final AtomicLong previous = new AtomicLong(startTime);
188 >                final AtomicBoolean tryLongerDelay = new AtomicBoolean(false);
189 >                final int cycles = 8;
190                  final CountDownLatch done = new CountDownLatch(cycles);
191 <                Runnable task = new CheckedRunnable() {
192 <                    public void realRun() { done.countDown(); }};
193 <                ScheduledFuture h =
191 >                final int d = delay;
192 >                final Runnable task = new CheckedRunnable() {
193 >                    public void realRun() {
194 >                        long now = System.nanoTime();
195 >                        long elapsedMillis
196 >                            = NANOSECONDS.toMillis(now - previous.get());
197 >                        if (done.getCount() == cycles) { // first execution
198 >                            if (elapsedMillis >= d)
199 >                                tryLongerDelay.set(true);
200 >                        } else {
201 >                            assertTrue(elapsedMillis >= d);
202 >                            if (elapsedMillis >= 2 * d)
203 >                                tryLongerDelay.set(true);
204 >                        }
205 >                        previous.set(now);
206 >                        done.countDown();
207 >                    }};
208 >                final ScheduledFuture periodicTask =
209                      p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
210 <                await(done);
211 <                h.cancel(true);
212 <                double normalizedTime =
213 <                    (double) millisElapsedSince(startTime) / delay;
214 <                if (normalizedTime >= cycles - 1 &&
215 <                    normalizedTime <= cycles)
210 >                final int totalDelayMillis = (cycles - 1) * delay;
211 >                await(done, totalDelayMillis + cycles * LONG_DELAY_MS);
212 >                periodicTask.cancel(true);
213 >                final long elapsedMillis = millisElapsedSince(startTime);
214 >                assertTrue(elapsedMillis >= totalDelayMillis);
215 >                if (!tryLongerDelay.get())
216                      return;
217 +                // else retry with longer delay
218              }
219 <            throw new AssertionError("unexpected execution rate");
219 >            fail("unexpected execution rate");
220          }
221      }
222  
# Line 337 | Line 363 | public class ScheduledExecutorTest exten
363                  public void realRun() throws InterruptedException {
364                      threadStarted.countDown();
365                      assertEquals(0, p.getCompletedTaskCount());
366 <                    threadProceed.await();
366 >                    await(threadProceed);
367                      threadDone.countDown();
368                  }});
369              await(threadStarted);
370              assertEquals(0, p.getCompletedTaskCount());
371              threadProceed.countDown();
372 <            threadDone.await();
372 >            await(threadDone);
373              long startTime = System.nanoTime();
374              while (p.getCompletedTaskCount() != 1) {
375                  if (millisElapsedSince(startTime) > LONG_DELAY_MS)
# Line 482 | Line 508 | public class ScheduledExecutorTest exten
508      }
509  
510      /**
511 +     * The default rejected execution handler is AbortPolicy.
512 +     */
513 +    public void testDefaultRejectedExecutionHandler() {
514 +        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
515 +        try (PoolCleaner cleaner = cleaner(p)) {
516 +            assertTrue(p.getRejectedExecutionHandler()
517 +                       instanceof ThreadPoolExecutor.AbortPolicy);
518 +        }
519 +    }
520 +
521 +    /**
522       * isShutdown is false before shutdown, true after
523       */
524      public void testIsShutdown() {
488
525          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
526 <        try {
527 <            assertFalse(p.isShutdown());
528 <        }
529 <        finally {
530 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
526 >        assertFalse(p.isShutdown());
527 >        try (PoolCleaner cleaner = cleaner(p)) {
528 >            try {
529 >                p.shutdown();
530 >                assertTrue(p.isShutdown());
531 >            } catch (SecurityException ok) {}
532          }
496        assertTrue(p.isShutdown());
533      }
534  
535      /**
# Line 709 | Line 745 | public class ScheduledExecutorTest exten
745       * - setContinueExistingPeriodicTasksAfterShutdownPolicy
746       */
747      public void testShutdown_cancellation() throws Exception {
712        Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE };
713        for (Boolean policy : allBooleans)
714    {
748          final int poolSize = 2;
749          final ScheduledThreadPoolExecutor p
750              = new ScheduledThreadPoolExecutor(poolSize);
751 <        final boolean effectiveDelayedPolicy = (policy != Boolean.FALSE);
752 <        final boolean effectivePeriodicPolicy = (policy == Boolean.TRUE);
753 <        final boolean effectiveRemovePolicy = (policy == Boolean.TRUE);
754 <        if (policy != null) {
755 <            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(policy);
756 <            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(policy);
757 <            p.setRemoveOnCancelPolicy(policy);
758 <        }
751 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
752 >        final boolean effectiveDelayedPolicy;
753 >        final boolean effectivePeriodicPolicy;
754 >        final boolean effectiveRemovePolicy;
755 >
756 >        if (rnd.nextBoolean())
757 >            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(
758 >                effectiveDelayedPolicy = rnd.nextBoolean());
759 >        else
760 >            effectiveDelayedPolicy = true;
761          assertEquals(effectiveDelayedPolicy,
762                       p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
763 +
764 +        if (rnd.nextBoolean())
765 +            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(
766 +                effectivePeriodicPolicy = rnd.nextBoolean());
767 +        else
768 +            effectivePeriodicPolicy = false;
769          assertEquals(effectivePeriodicPolicy,
770                       p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
771 +
772 +        if (rnd.nextBoolean())
773 +            p.setRemoveOnCancelPolicy(
774 +                effectiveRemovePolicy = rnd.nextBoolean());
775 +        else
776 +            effectiveRemovePolicy = false;
777          assertEquals(effectiveRemovePolicy,
778                       p.getRemoveOnCancelPolicy());
779 +
780          // Strategy: Wedge the pool with poolSize "blocker" threads
781          final AtomicInteger ran = new AtomicInteger(0);
782          final CountDownLatch poolBlocked = new CountDownLatch(poolSize);
# Line 738 | Line 786 | public class ScheduledExecutorTest exten
786          Runnable task = new CheckedRunnable() { public void realRun()
787                                                      throws InterruptedException {
788              poolBlocked.countDown();
789 <            assertTrue(unblock.await(LONG_DELAY_MS, MILLISECONDS));
789 >            await(unblock);
790              ran.getAndIncrement();
791          }};
792          List<Future<?>> blockers = new ArrayList<>();
# Line 746 | Line 794 | public class ScheduledExecutorTest exten
794          List<Future<?>> delayeds = new ArrayList<>();
795          for (int i = 0; i < poolSize; i++)
796              blockers.add(p.submit(task));
797 <        assertTrue(poolBlocked.await(LONG_DELAY_MS, MILLISECONDS));
797 >        await(poolBlocked);
798  
799 <        periodics.add(p.scheduleAtFixedRate(countDowner(periodicLatch1),
800 <                                            1, 1, MILLISECONDS));
801 <        periodics.add(p.scheduleWithFixedDelay(countDowner(periodicLatch2),
802 <                                               1, 1, MILLISECONDS));
799 >        periodics.add(p.scheduleAtFixedRate(
800 >                          countDowner(periodicLatch1), 1, 1, MILLISECONDS));
801 >        periodics.add(p.scheduleWithFixedDelay(
802 >                          countDowner(periodicLatch2), 1, 1, MILLISECONDS));
803          delayeds.add(p.schedule(task, 1, MILLISECONDS));
804  
805          assertTrue(p.getQueue().containsAll(periodics));
# Line 773 | Line 821 | public class ScheduledExecutorTest exten
821              assertEquals(effectiveDelayedPolicy,
822                           p.getQueue().containsAll(delayeds));
823          }
824 <        // Release all pool threads
777 <        unblock.countDown();
824 >        unblock.countDown();    // Release all pool threads
825  
826 <        for (Future<?> delayed : delayeds) {
827 <            if (effectiveDelayedPolicy) {
781 <                assertNull(delayed.get());
782 <            }
783 <        }
826 >        if (effectiveDelayedPolicy)
827 >            for (Future<?> delayed : delayeds) assertNull(delayed.get());
828          if (effectivePeriodicPolicy) {
829 <            assertTrue(periodicLatch1.await(LONG_DELAY_MS, MILLISECONDS));
830 <            assertTrue(periodicLatch2.await(LONG_DELAY_MS, MILLISECONDS));
829 >            await(periodicLatch1);
830 >            await(periodicLatch2);
831              for (Future<?> periodic : periodics) {
832                  assertTrue(periodic.cancel(false));
833                  assertTrue(periodic.isCancelled());
834                  assertTrue(periodic.isDone());
835              }
836          }
837 +        for (Future<?> blocker : blockers) assertNull(blocker.get());
838          assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
839          assertTrue(p.isTerminated());
840 +
841 +        for (Future<?> future : delayeds) {
842 +            assertTrue(effectiveDelayedPolicy ^ future.isCancelled());
843 +            assertTrue(future.isDone());
844 +        }
845 +        for (Future<?> future : periodics)
846 +            assertTrue(future.isCancelled());
847 +        for (Future<?> future : blockers)
848 +            assertNull(future.get());
849          assertEquals(2 + (effectiveDelayedPolicy ? 1 : 0), ran.get());
850 <    }}
850 >    }
851  
852      /**
853       * completed submit of callable returns result
# Line 864 | Line 918 | public class ScheduledExecutorTest exten
918          CountDownLatch latch = new CountDownLatch(1);
919          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
920          try (PoolCleaner cleaner = cleaner(e)) {
921 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
921 >            List<Callable<String>> l = new ArrayList<>();
922              l.add(latchAwaitingStringTask(latch));
923              l.add(null);
924              try {
# Line 881 | Line 935 | public class ScheduledExecutorTest exten
935      public void testInvokeAny4() throws Exception {
936          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
937          try (PoolCleaner cleaner = cleaner(e)) {
938 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
938 >            List<Callable<String>> l = new ArrayList<>();
939              l.add(new NPETask());
940              try {
941                  e.invokeAny(l);
# Line 898 | Line 952 | public class ScheduledExecutorTest exten
952      public void testInvokeAny5() throws Exception {
953          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
954          try (PoolCleaner cleaner = cleaner(e)) {
955 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
955 >            List<Callable<String>> l = new ArrayList<>();
956              l.add(new StringTask());
957              l.add(new StringTask());
958              String result = e.invokeAny(l);
# Line 936 | Line 990 | public class ScheduledExecutorTest exten
990      public void testInvokeAll3() throws Exception {
991          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
992          try (PoolCleaner cleaner = cleaner(e)) {
993 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
993 >            List<Callable<String>> l = new ArrayList<>();
994              l.add(new StringTask());
995              l.add(null);
996              try {
# Line 952 | Line 1006 | public class ScheduledExecutorTest exten
1006      public void testInvokeAll4() throws Exception {
1007          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1008          try (PoolCleaner cleaner = cleaner(e)) {
1009 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1009 >            List<Callable<String>> l = new ArrayList<>();
1010              l.add(new NPETask());
1011              List<Future<String>> futures = e.invokeAll(l);
1012              assertEquals(1, futures.size());
# Line 971 | Line 1025 | public class ScheduledExecutorTest exten
1025      public void testInvokeAll5() throws Exception {
1026          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1027          try (PoolCleaner cleaner = cleaner(e)) {
1028 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1028 >            List<Callable<String>> l = new ArrayList<>();
1029              l.add(new StringTask());
1030              l.add(new StringTask());
1031              List<Future<String>> futures = e.invokeAll(l);
# Line 1000 | Line 1054 | public class ScheduledExecutorTest exten
1054      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1055          final ExecutorService e = new ScheduledThreadPoolExecutor(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 StringTask());
1059              try {
1060                  e.invokeAny(l, MEDIUM_DELAY_MS, null);
# Line 1029 | Line 1083 | public class ScheduledExecutorTest exten
1083          CountDownLatch latch = new CountDownLatch(1);
1084          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1085          try (PoolCleaner cleaner = cleaner(e)) {
1086 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1086 >            List<Callable<String>> l = new ArrayList<>();
1087              l.add(latchAwaitingStringTask(latch));
1088              l.add(null);
1089              try {
# Line 1047 | Line 1101 | public class ScheduledExecutorTest exten
1101          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1102          try (PoolCleaner cleaner = cleaner(e)) {
1103              long startTime = System.nanoTime();
1104 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1104 >            List<Callable<String>> l = new ArrayList<>();
1105              l.add(new NPETask());
1106              try {
1107                  e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1066 | Line 1120 | public class ScheduledExecutorTest exten
1120          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1121          try (PoolCleaner cleaner = cleaner(e)) {
1122              long startTime = System.nanoTime();
1123 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1123 >            List<Callable<String>> l = new ArrayList<>();
1124              l.add(new StringTask());
1125              l.add(new StringTask());
1126              String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1094 | Line 1148 | public class ScheduledExecutorTest exten
1148      public void testTimedInvokeAllNullTimeUnit() throws Exception {
1149          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1150          try (PoolCleaner cleaner = cleaner(e)) {
1151 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1151 >            List<Callable<String>> l = new ArrayList<>();
1152              l.add(new StringTask());
1153              try {
1154                  e.invokeAll(l, MEDIUM_DELAY_MS, null);
# Line 1121 | Line 1175 | public class ScheduledExecutorTest exten
1175      public void testTimedInvokeAll3() throws Exception {
1176          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1177          try (PoolCleaner cleaner = cleaner(e)) {
1178 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1178 >            List<Callable<String>> l = new ArrayList<>();
1179              l.add(new StringTask());
1180              l.add(null);
1181              try {
# Line 1137 | Line 1191 | public class ScheduledExecutorTest exten
1191      public void testTimedInvokeAll4() throws Exception {
1192          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1193          try (PoolCleaner cleaner = cleaner(e)) {
1194 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1194 >            List<Callable<String>> l = new ArrayList<>();
1195              l.add(new NPETask());
1196              List<Future<String>> futures =
1197                  e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1157 | Line 1211 | public class ScheduledExecutorTest exten
1211      public void testTimedInvokeAll5() throws Exception {
1212          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1213          try (PoolCleaner cleaner = cleaner(e)) {
1214 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1214 >            List<Callable<String>> l = new ArrayList<>();
1215              l.add(new StringTask());
1216              l.add(new StringTask());
1217              List<Future<String>> futures =
# Line 1206 | Line 1260 | public class ScheduledExecutorTest exten
1260          }
1261      }
1262  
1263 +    /**
1264 +     * A fixed delay task with overflowing period should not prevent a
1265 +     * one-shot task from executing.
1266 +     * https://bugs.openjdk.java.net/browse/JDK-8051859
1267 +     */
1268 +    public void testScheduleWithFixedDelay_overflow() throws Exception {
1269 +        final CountDownLatch delayedDone = new CountDownLatch(1);
1270 +        final CountDownLatch immediateDone = new CountDownLatch(1);
1271 +        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
1272 +        try (PoolCleaner cleaner = cleaner(p)) {
1273 +            final Runnable immediate = new Runnable() { public void run() {
1274 +                immediateDone.countDown();
1275 +            }};
1276 +            final Runnable delayed = new Runnable() { public void run() {
1277 +                delayedDone.countDown();
1278 +                p.submit(immediate);
1279 +            }};
1280 +            p.scheduleWithFixedDelay(delayed, 0L, Long.MAX_VALUE, SECONDS);
1281 +            await(delayedDone);
1282 +            await(immediateDone);
1283 +        }
1284 +    }
1285 +
1286   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines