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.66 by jsr166, Mon Oct 5 21:54:33 2015 UTC vs.
Revision 1.92 by jsr166, Wed Mar 29 17:47:16 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 + import java.util.stream.Stream;
33  
34   import junit.framework.Test;
35   import junit.framework.TestSuite;
# Line 42 | Line 46 | public class ScheduledExecutorTest exten
46       * execute successfully executes a runnable
47       */
48      public void testExecute() throws InterruptedException {
49 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
49 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
50          try (PoolCleaner cleaner = cleaner(p)) {
51              final CountDownLatch done = new CountDownLatch(1);
52              final Runnable task = new CheckedRunnable() {
53                  public void realRun() { done.countDown(); }};
54              p.execute(task);
55 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
55 >            await(done);
56          }
57      }
58  
# Line 56 | Line 60 | public class ScheduledExecutorTest exten
60       * delayed schedule of callable successfully executes after delay
61       */
62      public void testSchedule1() throws Exception {
63 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
63 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
64          try (PoolCleaner cleaner = cleaner(p)) {
65              final long startTime = System.nanoTime();
66              final CountDownLatch done = new CountDownLatch(1);
# Line 77 | Line 81 | public class ScheduledExecutorTest exten
81       * delayed schedule of runnable successfully executes after delay
82       */
83      public void testSchedule3() throws Exception {
84 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
84 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
85          try (PoolCleaner cleaner = cleaner(p)) {
86              final long startTime = System.nanoTime();
87              final CountDownLatch done = new CountDownLatch(1);
# Line 97 | Line 101 | public class ScheduledExecutorTest exten
101       * scheduleAtFixedRate executes runnable after given initial delay
102       */
103      public void testSchedule4() throws Exception {
104 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
104 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
105          try (PoolCleaner cleaner = cleaner(p)) {
106              final long startTime = System.nanoTime();
107              final CountDownLatch done = new CountDownLatch(1);
# Line 119 | Line 123 | public class ScheduledExecutorTest exten
123       * scheduleWithFixedDelay executes runnable after given initial delay
124       */
125      public void testSchedule5() throws Exception {
126 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
126 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
127          try (PoolCleaner cleaner = cleaner(p)) {
128              final long startTime = System.nanoTime();
129              final CountDownLatch done = new CountDownLatch(1);
# Line 143 | Line 147 | public class ScheduledExecutorTest exten
147      }
148  
149      /**
150 <     * scheduleAtFixedRate executes series of tasks at given rate
150 >     * scheduleAtFixedRate executes series of tasks at given rate.
151 >     * Eventually, it must hold that:
152 >     *   cycles - 1 <= elapsedMillis/delay < cycles
153       */
154      public void testFixedRateSequence() throws InterruptedException {
155 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
155 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
156          try (PoolCleaner cleaner = cleaner(p)) {
157              for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
158 <                long startTime = System.nanoTime();
159 <                int cycles = 10;
158 >                final long startTime = System.nanoTime();
159 >                final int cycles = 8;
160                  final CountDownLatch done = new CountDownLatch(cycles);
161 <                Runnable task = new CheckedRunnable() {
161 >                final Runnable task = new CheckedRunnable() {
162                      public void realRun() { done.countDown(); }};
163 <                ScheduledFuture h =
163 >                final ScheduledFuture periodicTask =
164                      p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
165 <                done.await();
166 <                h.cancel(true);
167 <                double normalizedTime =
168 <                    (double) millisElapsedSince(startTime) / delay;
169 <                if (normalizedTime >= cycles - 1 &&
170 <                    normalizedTime <= cycles)
165 >                final int totalDelayMillis = (cycles - 1) * delay;
166 >                await(done, totalDelayMillis + LONG_DELAY_MS);
167 >                periodicTask.cancel(true);
168 >                final long elapsedMillis = millisElapsedSince(startTime);
169 >                assertTrue(elapsedMillis >= totalDelayMillis);
170 >                if (elapsedMillis <= cycles * delay)
171                      return;
172 +                // else retry with longer delay
173              }
174 <            throw new AssertionError("unexpected execution rate");
174 >            fail("unexpected execution rate");
175          }
176      }
177  
178      /**
179 <     * scheduleWithFixedDelay executes series of tasks with given period
179 >     * scheduleWithFixedDelay executes series of tasks with given period.
180 >     * Eventually, it must hold that each task starts at least delay and at
181 >     * most 2 * delay after the termination of the previous task.
182       */
183      public void testFixedDelaySequence() throws InterruptedException {
184 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
184 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
185          try (PoolCleaner cleaner = cleaner(p)) {
186              for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
187 <                long startTime = System.nanoTime();
188 <                int cycles = 10;
187 >                final long startTime = System.nanoTime();
188 >                final AtomicLong previous = new AtomicLong(startTime);
189 >                final AtomicBoolean tryLongerDelay = new AtomicBoolean(false);
190 >                final int cycles = 8;
191                  final CountDownLatch done = new CountDownLatch(cycles);
192 <                Runnable task = new CheckedRunnable() {
193 <                    public void realRun() { done.countDown(); }};
194 <                ScheduledFuture h =
192 >                final int d = delay;
193 >                final Runnable task = new CheckedRunnable() {
194 >                    public void realRun() {
195 >                        long now = System.nanoTime();
196 >                        long elapsedMillis
197 >                            = NANOSECONDS.toMillis(now - previous.get());
198 >                        if (done.getCount() == cycles) { // first execution
199 >                            if (elapsedMillis >= d)
200 >                                tryLongerDelay.set(true);
201 >                        } else {
202 >                            assertTrue(elapsedMillis >= d);
203 >                            if (elapsedMillis >= 2 * d)
204 >                                tryLongerDelay.set(true);
205 >                        }
206 >                        previous.set(now);
207 >                        done.countDown();
208 >                    }};
209 >                final ScheduledFuture periodicTask =
210                      p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
211 <                done.await();
212 <                h.cancel(true);
213 <                double normalizedTime =
214 <                    (double) millisElapsedSince(startTime) / delay;
215 <                if (normalizedTime >= cycles - 1 &&
216 <                    normalizedTime <= cycles)
211 >                final int totalDelayMillis = (cycles - 1) * delay;
212 >                await(done, totalDelayMillis + cycles * LONG_DELAY_MS);
213 >                periodicTask.cancel(true);
214 >                final long elapsedMillis = millisElapsedSince(startTime);
215 >                assertTrue(elapsedMillis >= totalDelayMillis);
216 >                if (!tryLongerDelay.get())
217                      return;
218 +                // else retry with longer delay
219              }
220 <            throw new AssertionError("unexpected execution rate");
220 >            fail("unexpected execution rate");
221          }
222      }
223  
# Line 198 | Line 225 | public class ScheduledExecutorTest exten
225       * execute(null) throws NPE
226       */
227      public void testExecuteNull() throws InterruptedException {
228 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
228 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
229          try (PoolCleaner cleaner = cleaner(p)) {
230              try {
231                  p.execute(null);
# Line 225 | Line 252 | public class ScheduledExecutorTest exten
252       * execute throws RejectedExecutionException if shutdown
253       */
254      public void testSchedule1_RejectedExecutionException() throws InterruptedException {
255 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
255 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
256          try (PoolCleaner cleaner = cleaner(p)) {
257              try {
258                  p.shutdown();
# Line 241 | Line 268 | public class ScheduledExecutorTest exten
268       * schedule throws RejectedExecutionException if shutdown
269       */
270      public void testSchedule2_RejectedExecutionException() throws InterruptedException {
271 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
271 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
272          try (PoolCleaner cleaner = cleaner(p)) {
273              try {
274                  p.shutdown();
# Line 257 | Line 284 | public class ScheduledExecutorTest exten
284       * schedule callable throws RejectedExecutionException if shutdown
285       */
286      public void testSchedule3_RejectedExecutionException() throws InterruptedException {
287 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
287 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
288          try (PoolCleaner cleaner = cleaner(p)) {
289              try {
290                  p.shutdown();
# Line 273 | Line 300 | public class ScheduledExecutorTest exten
300       * scheduleAtFixedRate throws RejectedExecutionException if shutdown
301       */
302      public void testScheduleAtFixedRate1_RejectedExecutionException() throws InterruptedException {
303 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
303 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
304          try (PoolCleaner cleaner = cleaner(p)) {
305              try {
306                  p.shutdown();
# Line 289 | Line 316 | public class ScheduledExecutorTest exten
316       * scheduleWithFixedDelay throws RejectedExecutionException if shutdown
317       */
318      public void testScheduleWithFixedDelay1_RejectedExecutionException() throws InterruptedException {
319 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
319 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
320          try (PoolCleaner cleaner = cleaner(p)) {
321              try {
322                  p.shutdown();
# Line 306 | Line 333 | public class ScheduledExecutorTest exten
333       * thread becomes active
334       */
335      public void testGetActiveCount() throws InterruptedException {
336 +        final CountDownLatch done = new CountDownLatch(1);
337          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
338 <        try (PoolCleaner cleaner = cleaner(p)) {
338 >        try (PoolCleaner cleaner = cleaner(p, done)) {
339              final CountDownLatch threadStarted = new CountDownLatch(1);
312            final CountDownLatch done = new CountDownLatch(1);
340              assertEquals(0, p.getActiveCount());
341              p.execute(new CheckedRunnable() {
342                  public void realRun() throws InterruptedException {
343                      threadStarted.countDown();
344                      assertEquals(1, p.getActiveCount());
345 <                    done.await();
345 >                    await(done);
346                  }});
347 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
347 >            await(threadStarted);
348              assertEquals(1, p.getActiveCount());
322            done.countDown();
349          }
350      }
351  
# Line 338 | 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 373 | Line 399 | public class ScheduledExecutorTest exten
399          final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(THREADS);
400          final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
401          final CountDownLatch done = new CountDownLatch(1);
402 <        try (PoolCleaner cleaner = cleaner(p)) {
402 >        try (PoolCleaner cleaner = cleaner(p, done)) {
403              assertEquals(0, p.getLargestPoolSize());
404              for (int i = 0; i < THREADS; i++)
405                  p.execute(new CheckedRunnable() {
406                      public void realRun() throws InterruptedException {
407                          threadsStarted.countDown();
408 <                        done.await();
408 >                        await(done);
409                          assertEquals(THREADS, p.getLargestPoolSize());
410                      }});
411 <            assertTrue(threadsStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
411 >            await(threadsStarted);
412              assertEquals(THREADS, p.getLargestPoolSize());
387            done.countDown();
413          }
414          assertEquals(THREADS, p.getLargestPoolSize());
415      }
# Line 397 | Line 422 | public class ScheduledExecutorTest exten
422          final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
423          final CountDownLatch threadStarted = new CountDownLatch(1);
424          final CountDownLatch done = new CountDownLatch(1);
425 <        try (PoolCleaner cleaner = cleaner(p)) {
425 >        try (PoolCleaner cleaner = cleaner(p, done)) {
426              assertEquals(0, p.getPoolSize());
427              p.execute(new CheckedRunnable() {
428                  public void realRun() throws InterruptedException {
429                      threadStarted.countDown();
430                      assertEquals(1, p.getPoolSize());
431 <                    done.await();
431 >                    await(done);
432                  }});
433 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
433 >            await(threadStarted);
434              assertEquals(1, p.getPoolSize());
410            done.countDown();
435          }
436      }
437  
# Line 426 | Line 450 | public class ScheduledExecutorTest exten
450              p.execute(new CheckedRunnable() {
451                  public void realRun() throws InterruptedException {
452                      threadStarted.countDown();
453 <                    done.await();
453 >                    await(done);
454                  }});
455 <            assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS));
455 >            await(threadStarted);
456              assertEquals(1, p.getTaskCount());
457              assertEquals(0, p.getCompletedTaskCount());
458              for (int i = 0; i < TASKS; i++) {
# Line 437 | Line 461 | public class ScheduledExecutorTest exten
461                      public void realRun() throws InterruptedException {
462                          threadStarted.countDown();
463                          assertEquals(1 + TASKS, p.getTaskCount());
464 <                        done.await();
464 >                        await(done);
465                      }});
466              }
467              assertEquals(1 + TASKS, p.getTaskCount());
# Line 464 | Line 488 | public class ScheduledExecutorTest exten
488       */
489      public void testSetThreadFactory() throws InterruptedException {
490          ThreadFactory threadFactory = new SimpleThreadFactory();
491 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
491 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
492          try (PoolCleaner cleaner = cleaner(p)) {
493              p.setThreadFactory(threadFactory);
494              assertSame(threadFactory, p.getThreadFactory());
# Line 475 | Line 499 | public class ScheduledExecutorTest exten
499       * setThreadFactory(null) throws NPE
500       */
501      public void testSetThreadFactoryNull() throws InterruptedException {
502 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
502 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
503          try (PoolCleaner cleaner = cleaner(p)) {
504              try {
505                  p.setThreadFactory(null);
# Line 485 | 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() {
526 <
527 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
528 <        try {
529 <            assertFalse(p.isShutdown());
530 <        }
531 <        finally {
532 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
526 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
527 >        assertFalse(p.isShutdown());
528 >        try (PoolCleaner cleaner = cleaner(p)) {
529 >            try {
530 >                p.shutdown();
531 >                assertTrue(p.isShutdown());
532 >            } catch (SecurityException ok) {}
533          }
499        assertTrue(p.isShutdown());
534      }
535  
536      /**
# Line 512 | Line 546 | public class ScheduledExecutorTest exten
546                  public void realRun() throws InterruptedException {
547                      assertFalse(p.isTerminated());
548                      threadStarted.countDown();
549 <                    done.await();
549 >                    await(done);
550                  }});
551 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
551 >            await(threadStarted);
552              assertFalse(p.isTerminating());
553              done.countDown();
554              try { p.shutdown(); } catch (SecurityException ok) { return; }
# Line 536 | Line 570 | public class ScheduledExecutorTest exten
570                  public void realRun() throws InterruptedException {
571                      assertFalse(p.isTerminating());
572                      threadStarted.countDown();
573 <                    done.await();
573 >                    await(done);
574                  }});
575 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
575 >            await(threadStarted);
576              assertFalse(p.isTerminating());
577              done.countDown();
578              try { p.shutdown(); } catch (SecurityException ok) { return; }
# Line 552 | Line 586 | public class ScheduledExecutorTest exten
586       * getQueue returns the work queue, which contains queued tasks
587       */
588      public void testGetQueue() throws InterruptedException {
589 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
590 <        try (PoolCleaner cleaner = cleaner(p)) {
589 >        final CountDownLatch done = new CountDownLatch(1);
590 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
591 >        try (PoolCleaner cleaner = cleaner(p, done)) {
592              final CountDownLatch threadStarted = new CountDownLatch(1);
558            final CountDownLatch done = new CountDownLatch(1);
593              ScheduledFuture[] tasks = new ScheduledFuture[5];
594              for (int i = 0; i < tasks.length; i++) {
595                  Runnable r = new CheckedRunnable() {
596                      public void realRun() throws InterruptedException {
597                          threadStarted.countDown();
598 <                        done.await();
598 >                        await(done);
599                      }};
600                  tasks[i] = p.schedule(r, 1, MILLISECONDS);
601              }
602 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
602 >            await(threadStarted);
603              BlockingQueue<Runnable> q = p.getQueue();
604              assertTrue(q.contains(tasks[tasks.length - 1]));
605              assertFalse(q.contains(tasks[0]));
572            done.countDown();
606          }
607      }
608  
# Line 577 | Line 610 | public class ScheduledExecutorTest exten
610       * remove(task) removes queued task, and fails to remove active task
611       */
612      public void testRemove() throws InterruptedException {
613 +        final CountDownLatch done = new CountDownLatch(1);
614          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
615 <        try (PoolCleaner cleaner = cleaner(p)) {
615 >        try (PoolCleaner cleaner = cleaner(p, done)) {
616              ScheduledFuture[] tasks = new ScheduledFuture[5];
617              final CountDownLatch threadStarted = new CountDownLatch(1);
584            final CountDownLatch done = new CountDownLatch(1);
618              for (int i = 0; i < tasks.length; i++) {
619                  Runnable r = new CheckedRunnable() {
620                      public void realRun() throws InterruptedException {
621                          threadStarted.countDown();
622 <                        done.await();
622 >                        await(done);
623                      }};
624                  tasks[i] = p.schedule(r, 1, MILLISECONDS);
625              }
626 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
626 >            await(threadStarted);
627              BlockingQueue<Runnable> q = p.getQueue();
628              assertFalse(p.remove((Runnable)tasks[0]));
629              assertTrue(q.contains((Runnable)tasks[4]));
# Line 601 | Line 634 | public class ScheduledExecutorTest exten
634              assertTrue(q.contains((Runnable)tasks[3]));
635              assertTrue(p.remove((Runnable)tasks[3]));
636              assertFalse(q.contains((Runnable)tasks[3]));
604            done.countDown();
637          }
638      }
639  
# Line 654 | Line 686 | public class ScheduledExecutorTest exten
686          }};
687          for (int i = 0; i < count; i++)
688              p.execute(waiter);
689 <        assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS));
689 >        await(threadsStarted);
690          assertEquals(poolSize, p.getActiveCount());
691          assertEquals(0, p.getCompletedTaskCount());
692          final List<Runnable> queuedTasks;
# Line 677 | Line 709 | public class ScheduledExecutorTest exten
709       * and those tasks are drained from the queue
710       */
711      public void testShutdownNow_delayedTasks() throws InterruptedException {
712 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
712 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
713          List<ScheduledFuture> tasks = new ArrayList<>();
714          for (int i = 0; i < 3; i++) {
715              Runnable r = new NoOpRunnable();
# Line 714 | Line 746 | public class ScheduledExecutorTest exten
746       * - setContinueExistingPeriodicTasksAfterShutdownPolicy
747       */
748      public void testShutdown_cancellation() throws Exception {
749 <        Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE };
718 <        for (Boolean policy : allBooleans)
719 <    {
720 <        final int poolSize = 2;
749 >        final int poolSize = 4;
750          final ScheduledThreadPoolExecutor p
751              = new ScheduledThreadPoolExecutor(poolSize);
752 <        final boolean effectiveDelayedPolicy = (policy != Boolean.FALSE);
753 <        final boolean effectivePeriodicPolicy = (policy == Boolean.TRUE);
754 <        final boolean effectiveRemovePolicy = (policy == Boolean.TRUE);
755 <        if (policy != null) {
756 <            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(policy);
757 <            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(policy);
758 <            p.setRemoveOnCancelPolicy(policy);
759 <        }
752 >        final BlockingQueue<Runnable> q = p.getQueue();
753 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
754 >        final long delay = rnd.nextInt(2);
755 >        final int rounds = rnd.nextInt(1, 3);
756 >        final boolean effectiveDelayedPolicy;
757 >        final boolean effectivePeriodicPolicy;
758 >        final boolean effectiveRemovePolicy;
759 >
760 >        if (rnd.nextBoolean())
761 >            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(
762 >                effectiveDelayedPolicy = rnd.nextBoolean());
763 >        else
764 >            effectiveDelayedPolicy = true;
765          assertEquals(effectiveDelayedPolicy,
766                       p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
767 +
768 +        if (rnd.nextBoolean())
769 +            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(
770 +                effectivePeriodicPolicy = rnd.nextBoolean());
771 +        else
772 +            effectivePeriodicPolicy = false;
773          assertEquals(effectivePeriodicPolicy,
774                       p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
775 +
776 +        if (rnd.nextBoolean())
777 +            p.setRemoveOnCancelPolicy(
778 +                effectiveRemovePolicy = rnd.nextBoolean());
779 +        else
780 +            effectiveRemovePolicy = false;
781          assertEquals(effectiveRemovePolicy,
782                       p.getRemoveOnCancelPolicy());
783 <        // Strategy: Wedge the pool with poolSize "blocker" threads
783 >
784 >        final boolean periodicTasksContinue = effectivePeriodicPolicy && rnd.nextBoolean();
785 >
786 >        // Strategy: Wedge the pool with one wave of "blocker" tasks,
787 >        // then add a second wave that waits in the queue until unblocked.
788          final AtomicInteger ran = new AtomicInteger(0);
789          final CountDownLatch poolBlocked = new CountDownLatch(poolSize);
790          final CountDownLatch unblock = new CountDownLatch(1);
791 <        final CountDownLatch periodicLatch1 = new CountDownLatch(2);
742 <        final CountDownLatch periodicLatch2 = new CountDownLatch(2);
743 <        Runnable task = new CheckedRunnable() { public void realRun()
744 <                                                    throws InterruptedException {
745 <            poolBlocked.countDown();
746 <            assertTrue(unblock.await(LONG_DELAY_MS, MILLISECONDS));
747 <            ran.getAndIncrement();
748 <        }};
749 <        List<Future<?>> blockers = new ArrayList<>();
750 <        List<Future<?>> periodics = new ArrayList<>();
751 <        List<Future<?>> delayeds = new ArrayList<>();
752 <        for (int i = 0; i < poolSize; i++)
753 <            blockers.add(p.submit(task));
754 <        assertTrue(poolBlocked.await(LONG_DELAY_MS, MILLISECONDS));
755 <
756 <        periodics.add(p.scheduleAtFixedRate(countDowner(periodicLatch1),
757 <                                            1, 1, MILLISECONDS));
758 <        periodics.add(p.scheduleWithFixedDelay(countDowner(periodicLatch2),
759 <                                               1, 1, MILLISECONDS));
760 <        delayeds.add(p.schedule(task, 1, MILLISECONDS));
791 >        final RuntimeException exception = new RuntimeException();
792  
793 <        assertTrue(p.getQueue().containsAll(periodics));
794 <        assertTrue(p.getQueue().containsAll(delayeds));
795 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
796 <        assertTrue(p.isShutdown());
797 <        assertFalse(p.isTerminated());
798 <        for (Future<?> periodic : periodics) {
799 <            assertTrue(effectivePeriodicPolicy ^ periodic.isCancelled());
769 <            assertTrue(effectivePeriodicPolicy ^ periodic.isDone());
770 <        }
771 <        for (Future<?> delayed : delayeds) {
772 <            assertTrue(effectiveDelayedPolicy ^ delayed.isCancelled());
773 <            assertTrue(effectiveDelayedPolicy ^ delayed.isDone());
774 <        }
775 <        if (testImplementationDetails) {
776 <            assertEquals(effectivePeriodicPolicy,
777 <                         p.getQueue().containsAll(periodics));
778 <            assertEquals(effectiveDelayedPolicy,
779 <                         p.getQueue().containsAll(delayeds));
780 <        }
781 <        // Release all pool threads
782 <        unblock.countDown();
783 <
784 <        for (Future<?> delayed : delayeds) {
785 <            if (effectiveDelayedPolicy) {
786 <                assertNull(delayed.get());
793 >        class Task implements Runnable {
794 >            public void run() {
795 >                try {
796 >                    ran.getAndIncrement();
797 >                    poolBlocked.countDown();
798 >                    await(unblock);
799 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
800              }
801          }
802 <        if (effectivePeriodicPolicy) {
803 <            assertTrue(periodicLatch1.await(LONG_DELAY_MS, MILLISECONDS));
804 <            assertTrue(periodicLatch2.await(LONG_DELAY_MS, MILLISECONDS));
805 <            for (Future<?> periodic : periodics) {
806 <                assertTrue(periodic.cancel(false));
807 <                assertTrue(periodic.isCancelled());
808 <                assertTrue(periodic.isDone());
802 >
803 >        class PeriodicTask extends Task {
804 >            PeriodicTask(int rounds) { this.rounds = rounds; }
805 >            int rounds;
806 >            public void run() {
807 >                if (--rounds == 0) super.run();
808 >                // throw exception to surely terminate this periodic task,
809 >                // but in a separate execution and in a detectable way.
810 >                if (rounds == -1) throw exception;
811              }
812          }
813 +
814 +        Runnable task = new Task();
815 +
816 +        List<Future<?>> immediates = new ArrayList<>();
817 +        List<Future<?>> delayeds   = new ArrayList<>();
818 +        List<Future<?>> periodics  = new ArrayList<>();
819 +
820 +        immediates.add(p.submit(task));
821 +        delayeds.add(p.schedule(task, delay, MILLISECONDS));
822 +        periodics.add(p.scheduleAtFixedRate(
823 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
824 +        periodics.add(p.scheduleWithFixedDelay(
825 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
826 +
827 +        await(poolBlocked);
828 +
829 +        assertEquals(poolSize, ran.get());
830 +        assertEquals(poolSize, p.getActiveCount());
831 +        assertTrue(q.isEmpty());
832 +
833 +        // Add second wave of tasks.
834 +        immediates.add(p.submit(task));
835 +        delayeds.add(p.schedule(task, effectiveDelayedPolicy ? delay : LONG_DELAY_MS, MILLISECONDS));
836 +        periodics.add(p.scheduleAtFixedRate(
837 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
838 +        periodics.add(p.scheduleWithFixedDelay(
839 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
840 +
841 +        assertEquals(poolSize, q.size());
842 +        assertEquals(poolSize, ran.get());
843 +
844 +        immediates.forEach(
845 +            f -> assertTrue(((ScheduledFuture)f).getDelay(NANOSECONDS) <= 0L));
846 +
847 +        Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream())
848 +            .forEach(f -> assertFalse(f.isDone()));
849 +
850 +        try { p.shutdown(); } catch (SecurityException ok) { return; }
851 +        assertTrue(p.isShutdown());
852 +        assertTrue(p.isTerminating());
853 +        assertFalse(p.isTerminated());
854 +
855 +        if (rnd.nextBoolean())
856 +            assertThrows(
857 +                RejectedExecutionException.class,
858 +                () -> p.submit(task),
859 +                () -> p.schedule(task, 1, SECONDS),
860 +                () -> p.scheduleAtFixedRate(
861 +                    new PeriodicTask(1), 1, 1, SECONDS),
862 +                () -> p.scheduleWithFixedDelay(
863 +                    new PeriodicTask(2), 1, 1, SECONDS));
864 +
865 +        assertTrue(q.contains(immediates.get(1)));
866 +        assertTrue(!effectiveDelayedPolicy
867 +                   ^ q.contains(delayeds.get(1)));
868 +        assertTrue(!effectivePeriodicPolicy
869 +                   ^ q.containsAll(periodics.subList(2, 4)));
870 +
871 +        immediates.forEach(f -> assertFalse(f.isDone()));
872 +
873 +        assertFalse(delayeds.get(0).isDone());
874 +        if (effectiveDelayedPolicy)
875 +            assertFalse(delayeds.get(1).isDone());
876 +        else
877 +            assertTrue(delayeds.get(1).isCancelled());
878 +
879 +        if (effectivePeriodicPolicy)
880 +            periodics.forEach(
881 +                f -> {
882 +                    assertFalse(f.isDone());
883 +                    if (!periodicTasksContinue) {
884 +                        assertTrue(f.cancel(false));
885 +                        assertTrue(f.isCancelled());
886 +                    }
887 +                });
888 +        else {
889 +            periodics.subList(0, 2).forEach(f -> assertFalse(f.isDone()));
890 +            periodics.subList(2, 4).forEach(f -> assertTrue(f.isCancelled()));
891 +        }
892 +
893 +        unblock.countDown();    // Release all pool threads
894 +
895          assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
896 +        assertFalse(p.isTerminating());
897          assertTrue(p.isTerminated());
898 <        assertEquals(2 + (effectiveDelayedPolicy ? 1 : 0), ran.get());
899 <    }}
898 >
899 >        assertTrue(q.isEmpty());
900 >
901 >        Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream())
902 >            .forEach(f -> assertTrue(f.isDone()));
903 >
904 >        for (Future<?> f : immediates) assertNull(f.get());
905 >
906 >        assertNull(delayeds.get(0).get());
907 >        if (effectiveDelayedPolicy)
908 >            assertNull(delayeds.get(1).get());
909 >        else
910 >            assertTrue(delayeds.get(1).isCancelled());
911 >
912 >        if (periodicTasksContinue)
913 >            periodics.forEach(
914 >                f -> {
915 >                    try { f.get(); }
916 >                    catch (ExecutionException success) {
917 >                        assertSame(exception, success.getCause());
918 >                    }
919 >                    catch (Throwable fail) { threadUnexpectedException(fail); }
920 >                });
921 >        else
922 >            periodics.forEach(f -> assertTrue(f.isCancelled()));
923 >
924 >        assertEquals(poolSize + 1
925 >                     + (effectiveDelayedPolicy ? 1 : 0)
926 >                     + (periodicTasksContinue ? 2 : 0),
927 >                     ran.get());
928 >    }
929  
930      /**
931       * completed submit of callable returns result
# Line 869 | Line 996 | public class ScheduledExecutorTest exten
996          CountDownLatch latch = new CountDownLatch(1);
997          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
998          try (PoolCleaner cleaner = cleaner(e)) {
999 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
999 >            List<Callable<String>> l = new ArrayList<>();
1000              l.add(latchAwaitingStringTask(latch));
1001              l.add(null);
1002              try {
# Line 886 | Line 1013 | public class ScheduledExecutorTest exten
1013      public void testInvokeAny4() throws Exception {
1014          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1015          try (PoolCleaner cleaner = cleaner(e)) {
1016 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1016 >            List<Callable<String>> l = new ArrayList<>();
1017              l.add(new NPETask());
1018              try {
1019                  e.invokeAny(l);
# Line 903 | Line 1030 | public class ScheduledExecutorTest exten
1030      public void testInvokeAny5() throws Exception {
1031          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1032          try (PoolCleaner cleaner = cleaner(e)) {
1033 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1033 >            List<Callable<String>> l = new ArrayList<>();
1034              l.add(new StringTask());
1035              l.add(new StringTask());
1036              String result = e.invokeAny(l);
# Line 941 | Line 1068 | public class ScheduledExecutorTest exten
1068      public void testInvokeAll3() throws Exception {
1069          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1070          try (PoolCleaner cleaner = cleaner(e)) {
1071 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1071 >            List<Callable<String>> l = new ArrayList<>();
1072              l.add(new StringTask());
1073              l.add(null);
1074              try {
# Line 957 | Line 1084 | public class ScheduledExecutorTest exten
1084      public void testInvokeAll4() throws Exception {
1085          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1086          try (PoolCleaner cleaner = cleaner(e)) {
1087 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1087 >            List<Callable<String>> l = new ArrayList<>();
1088              l.add(new NPETask());
1089              List<Future<String>> futures = e.invokeAll(l);
1090              assertEquals(1, futures.size());
# Line 976 | Line 1103 | public class ScheduledExecutorTest exten
1103      public void testInvokeAll5() throws Exception {
1104          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1105          try (PoolCleaner cleaner = cleaner(e)) {
1106 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1106 >            List<Callable<String>> l = new ArrayList<>();
1107              l.add(new StringTask());
1108              l.add(new StringTask());
1109              List<Future<String>> futures = e.invokeAll(l);
# Line 1005 | Line 1132 | public class ScheduledExecutorTest exten
1132      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1133          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1134          try (PoolCleaner cleaner = cleaner(e)) {
1135 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1135 >            List<Callable<String>> l = new ArrayList<>();
1136              l.add(new StringTask());
1137              try {
1138                  e.invokeAny(l, MEDIUM_DELAY_MS, null);
# Line 1034 | Line 1161 | public class ScheduledExecutorTest exten
1161          CountDownLatch latch = new CountDownLatch(1);
1162          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1163          try (PoolCleaner cleaner = cleaner(e)) {
1164 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1164 >            List<Callable<String>> l = new ArrayList<>();
1165              l.add(latchAwaitingStringTask(latch));
1166              l.add(null);
1167              try {
# Line 1051 | Line 1178 | public class ScheduledExecutorTest exten
1178      public void testTimedInvokeAny4() throws Exception {
1179          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1180          try (PoolCleaner cleaner = cleaner(e)) {
1181 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1181 >            long startTime = System.nanoTime();
1182 >            List<Callable<String>> l = new ArrayList<>();
1183              l.add(new NPETask());
1184              try {
1185 <                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1185 >                e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1186                  shouldThrow();
1187              } catch (ExecutionException success) {
1188                  assertTrue(success.getCause() instanceof NullPointerException);
1189              }
1190 +            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1191          }
1192      }
1193  
# Line 1068 | Line 1197 | public class ScheduledExecutorTest exten
1197      public void testTimedInvokeAny5() throws Exception {
1198          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1199          try (PoolCleaner cleaner = cleaner(e)) {
1200 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1200 >            long startTime = System.nanoTime();
1201 >            List<Callable<String>> l = new ArrayList<>();
1202              l.add(new StringTask());
1203              l.add(new StringTask());
1204 <            String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1204 >            String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1205              assertSame(TEST_STRING, result);
1206 +            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1207          }
1208      }
1209  
# Line 1095 | Line 1226 | public class ScheduledExecutorTest exten
1226      public void testTimedInvokeAllNullTimeUnit() throws Exception {
1227          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1228          try (PoolCleaner cleaner = cleaner(e)) {
1229 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1229 >            List<Callable<String>> l = new ArrayList<>();
1230              l.add(new StringTask());
1231              try {
1232                  e.invokeAll(l, MEDIUM_DELAY_MS, null);
# Line 1122 | Line 1253 | public class ScheduledExecutorTest exten
1253      public void testTimedInvokeAll3() throws Exception {
1254          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1255          try (PoolCleaner cleaner = cleaner(e)) {
1256 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1256 >            List<Callable<String>> l = new ArrayList<>();
1257              l.add(new StringTask());
1258              l.add(null);
1259              try {
# Line 1138 | Line 1269 | public class ScheduledExecutorTest exten
1269      public void testTimedInvokeAll4() throws Exception {
1270          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1271          try (PoolCleaner cleaner = cleaner(e)) {
1272 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1272 >            List<Callable<String>> l = new ArrayList<>();
1273              l.add(new NPETask());
1274              List<Future<String>> futures =
1275 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1275 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1276              assertEquals(1, futures.size());
1277              try {
1278                  futures.get(0).get();
# Line 1158 | Line 1289 | public class ScheduledExecutorTest exten
1289      public void testTimedInvokeAll5() throws Exception {
1290          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1291          try (PoolCleaner cleaner = cleaner(e)) {
1292 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1292 >            List<Callable<String>> l = new ArrayList<>();
1293              l.add(new StringTask());
1294              l.add(new StringTask());
1295              List<Future<String>> futures =
# Line 1173 | Line 1304 | public class ScheduledExecutorTest exten
1304       * timed invokeAll(c) cancels tasks not completed by timeout
1305       */
1306      public void testTimedInvokeAll6() throws Exception {
1307 <        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1308 <        try (PoolCleaner cleaner = cleaner(e)) {
1309 <            for (long timeout = timeoutMillis();;) {
1307 >        for (long timeout = timeoutMillis();;) {
1308 >            final CountDownLatch done = new CountDownLatch(1);
1309 >            final Callable<String> waiter = new CheckedCallable<String>() {
1310 >                public String realCall() {
1311 >                    try { done.await(LONG_DELAY_MS, MILLISECONDS); }
1312 >                    catch (InterruptedException ok) {}
1313 >                    return "1"; }};
1314 >            final ExecutorService p = new ScheduledThreadPoolExecutor(2);
1315 >            try (PoolCleaner cleaner = cleaner(p, done)) {
1316                  List<Callable<String>> tasks = new ArrayList<>();
1317                  tasks.add(new StringTask("0"));
1318 <                tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1318 >                tasks.add(waiter);
1319                  tasks.add(new StringTask("2"));
1320                  long startTime = System.nanoTime();
1321                  List<Future<String>> futures =
1322 <                    e.invokeAll(tasks, timeout, MILLISECONDS);
1322 >                    p.invokeAll(tasks, timeout, MILLISECONDS);
1323                  assertEquals(tasks.size(), futures.size());
1324                  assertTrue(millisElapsedSince(startTime) >= timeout);
1325                  for (Future future : futures)
# Line 1201 | Line 1338 | public class ScheduledExecutorTest exten
1338          }
1339      }
1340  
1341 +    /**
1342 +     * A fixed delay task with overflowing period should not prevent a
1343 +     * one-shot task from executing.
1344 +     * https://bugs.openjdk.java.net/browse/JDK-8051859
1345 +     */
1346 +    public void testScheduleWithFixedDelay_overflow() throws Exception {
1347 +        final CountDownLatch delayedDone = new CountDownLatch(1);
1348 +        final CountDownLatch immediateDone = new CountDownLatch(1);
1349 +        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
1350 +        try (PoolCleaner cleaner = cleaner(p)) {
1351 +            final Runnable immediate = new Runnable() { public void run() {
1352 +                immediateDone.countDown();
1353 +            }};
1354 +            final Runnable delayed = new Runnable() { public void run() {
1355 +                delayedDone.countDown();
1356 +                p.submit(immediate);
1357 +            }};
1358 +            p.scheduleWithFixedDelay(delayed, 0L, Long.MAX_VALUE, SECONDS);
1359 +            await(delayedDone);
1360 +            await(immediateDone);
1361 +        }
1362 +    }
1363 +
1364   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines