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.62 by jsr166, Sun Oct 4 08:07:31 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 42 | Line 45 | public class ScheduledExecutorTest exten
45       * execute successfully executes a runnable
46       */
47      public void testExecute() throws InterruptedException {
48 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
48 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
49          try (PoolCleaner cleaner = cleaner(p)) {
50              final CountDownLatch done = new CountDownLatch(1);
51              final Runnable task = new CheckedRunnable() {
52                  public void realRun() { done.countDown(); }};
53              p.execute(task);
54 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
54 >            await(done);
55          }
56      }
57  
# Line 56 | Line 59 | public class ScheduledExecutorTest exten
59       * delayed schedule of callable successfully executes after delay
60       */
61      public void testSchedule1() throws Exception {
62 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
62 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
63          try (PoolCleaner cleaner = cleaner(p)) {
64              final long startTime = System.nanoTime();
65              final CountDownLatch done = new CountDownLatch(1);
# Line 77 | Line 80 | public class ScheduledExecutorTest exten
80       * delayed schedule of runnable successfully executes after delay
81       */
82      public void testSchedule3() throws Exception {
83 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
83 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
84          try (PoolCleaner cleaner = cleaner(p)) {
85              final long startTime = System.nanoTime();
86              final CountDownLatch done = new CountDownLatch(1);
# Line 97 | Line 100 | public class ScheduledExecutorTest exten
100       * scheduleAtFixedRate executes runnable after given initial delay
101       */
102      public void testSchedule4() throws Exception {
103 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
103 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
104          try (PoolCleaner cleaner = cleaner(p)) {
105              final long startTime = System.nanoTime();
106              final CountDownLatch done = new CountDownLatch(1);
# Line 119 | Line 122 | public class ScheduledExecutorTest exten
122       * scheduleWithFixedDelay executes runnable after given initial delay
123       */
124      public void testSchedule5() throws Exception {
125 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
125 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
126          try (PoolCleaner cleaner = cleaner(p)) {
127              final long startTime = System.nanoTime();
128              final CountDownLatch done = new CountDownLatch(1);
# 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 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
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 <                done.await();
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 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
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 <                done.await();
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 198 | Line 224 | public class ScheduledExecutorTest exten
224       * execute(null) throws NPE
225       */
226      public void testExecuteNull() throws InterruptedException {
227 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
227 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
228          try (PoolCleaner cleaner = cleaner(p)) {
229              try {
230                  p.execute(null);
# Line 225 | Line 251 | public class ScheduledExecutorTest exten
251       * execute throws RejectedExecutionException if shutdown
252       */
253      public void testSchedule1_RejectedExecutionException() throws InterruptedException {
254 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
254 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
255          try (PoolCleaner cleaner = cleaner(p)) {
256              try {
257                  p.shutdown();
# Line 241 | Line 267 | public class ScheduledExecutorTest exten
267       * schedule throws RejectedExecutionException if shutdown
268       */
269      public void testSchedule2_RejectedExecutionException() throws InterruptedException {
270 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
270 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
271          try (PoolCleaner cleaner = cleaner(p)) {
272              try {
273                  p.shutdown();
# Line 257 | Line 283 | public class ScheduledExecutorTest exten
283       * schedule callable throws RejectedExecutionException if shutdown
284       */
285      public void testSchedule3_RejectedExecutionException() throws InterruptedException {
286 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
286 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
287          try (PoolCleaner cleaner = cleaner(p)) {
288              try {
289                  p.shutdown();
# Line 273 | Line 299 | public class ScheduledExecutorTest exten
299       * scheduleAtFixedRate throws RejectedExecutionException if shutdown
300       */
301      public void testScheduleAtFixedRate1_RejectedExecutionException() throws InterruptedException {
302 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
302 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
303          try (PoolCleaner cleaner = cleaner(p)) {
304              try {
305                  p.shutdown();
# Line 289 | Line 315 | public class ScheduledExecutorTest exten
315       * scheduleWithFixedDelay throws RejectedExecutionException if shutdown
316       */
317      public void testScheduleWithFixedDelay1_RejectedExecutionException() throws InterruptedException {
318 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
318 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
319          try (PoolCleaner cleaner = cleaner(p)) {
320              try {
321                  p.shutdown();
# Line 306 | Line 332 | public class ScheduledExecutorTest exten
332       * thread becomes active
333       */
334      public void testGetActiveCount() throws InterruptedException {
335 +        final CountDownLatch done = new CountDownLatch(1);
336          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
337 <        try (PoolCleaner cleaner = cleaner(p)) {
337 >        try (PoolCleaner cleaner = cleaner(p, done)) {
338              final CountDownLatch threadStarted = new CountDownLatch(1);
312            final CountDownLatch done = new CountDownLatch(1);
339              assertEquals(0, p.getActiveCount());
340              p.execute(new CheckedRunnable() {
341                  public void realRun() throws InterruptedException {
342                      threadStarted.countDown();
343                      assertEquals(1, p.getActiveCount());
344 <                    done.await();
344 >                    await(done);
345                  }});
346 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
346 >            await(threadStarted);
347              assertEquals(1, p.getActiveCount());
322            done.countDown();
348          }
349      }
350  
# Line 338 | 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 373 | Line 398 | public class ScheduledExecutorTest exten
398          final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(THREADS);
399          final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
400          final CountDownLatch done = new CountDownLatch(1);
401 <        try (PoolCleaner cleaner = cleaner(p)) {
401 >        try (PoolCleaner cleaner = cleaner(p, done)) {
402              assertEquals(0, p.getLargestPoolSize());
403              for (int i = 0; i < THREADS; i++)
404                  p.execute(new CheckedRunnable() {
405                      public void realRun() throws InterruptedException {
406                          threadsStarted.countDown();
407 <                        done.await();
407 >                        await(done);
408                          assertEquals(THREADS, p.getLargestPoolSize());
409                      }});
410 <            assertTrue(threadsStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
410 >            await(threadsStarted);
411              assertEquals(THREADS, p.getLargestPoolSize());
387            done.countDown();
412          }
413          assertEquals(THREADS, p.getLargestPoolSize());
414      }
# Line 397 | Line 421 | public class ScheduledExecutorTest exten
421          final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
422          final CountDownLatch threadStarted = new CountDownLatch(1);
423          final CountDownLatch done = new CountDownLatch(1);
424 <        try (PoolCleaner cleaner = cleaner(p)) {
424 >        try (PoolCleaner cleaner = cleaner(p, done)) {
425              assertEquals(0, p.getPoolSize());
426              p.execute(new CheckedRunnable() {
427                  public void realRun() throws InterruptedException {
428                      threadStarted.countDown();
429                      assertEquals(1, p.getPoolSize());
430 <                    done.await();
430 >                    await(done);
431                  }});
432 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
432 >            await(threadStarted);
433              assertEquals(1, p.getPoolSize());
410            done.countDown();
434          }
435      }
436  
# Line 416 | Line 439 | public class ScheduledExecutorTest exten
439       * submitted
440       */
441      public void testGetTaskCount() throws InterruptedException {
442 +        final int TASKS = 3;
443 +        final CountDownLatch done = new CountDownLatch(1);
444          final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
445 <        try (PoolCleaner cleaner = cleaner(p)) {
445 >        try (PoolCleaner cleaner = cleaner(p, done)) {
446              final CountDownLatch threadStarted = new CountDownLatch(1);
422            final CountDownLatch done = new CountDownLatch(1);
423            final int TASKS = 5;
447              assertEquals(0, p.getTaskCount());
448 <            for (int i = 0; i < TASKS; i++)
448 >            assertEquals(0, p.getCompletedTaskCount());
449 >            p.execute(new CheckedRunnable() {
450 >                public void realRun() throws InterruptedException {
451 >                    threadStarted.countDown();
452 >                    await(done);
453 >                }});
454 >            await(threadStarted);
455 >            assertEquals(1, p.getTaskCount());
456 >            assertEquals(0, p.getCompletedTaskCount());
457 >            for (int i = 0; i < TASKS; i++) {
458 >                assertEquals(1 + i, p.getTaskCount());
459                  p.execute(new CheckedRunnable() {
460                      public void realRun() throws InterruptedException {
461                          threadStarted.countDown();
462 <                        done.await();
462 >                        assertEquals(1 + TASKS, p.getTaskCount());
463 >                        await(done);
464                      }});
465 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
466 <            assertEquals(TASKS, p.getTaskCount());
467 <            done.countDown();
465 >            }
466 >            assertEquals(1 + TASKS, p.getTaskCount());
467 >            assertEquals(0, p.getCompletedTaskCount());
468          }
469 +        assertEquals(1 + TASKS, p.getTaskCount());
470 +        assertEquals(1 + TASKS, p.getCompletedTaskCount());
471      }
472  
473      /**
474       * getThreadFactory returns factory in constructor if not set
475       */
476      public void testGetThreadFactory() throws InterruptedException {
477 <        ThreadFactory threadFactory = new SimpleThreadFactory();
478 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1, threadFactory);
479 <        assertSame(threadFactory, p.getThreadFactory());
480 <        joinPool(p);
477 >        final ThreadFactory threadFactory = new SimpleThreadFactory();
478 >        final ScheduledThreadPoolExecutor p =
479 >            new ScheduledThreadPoolExecutor(1, threadFactory);
480 >        try (PoolCleaner cleaner = cleaner(p)) {
481 >            assertSame(threadFactory, p.getThreadFactory());
482 >        }
483      }
484  
485      /**
# Line 449 | Line 487 | public class ScheduledExecutorTest exten
487       */
488      public void testSetThreadFactory() throws InterruptedException {
489          ThreadFactory threadFactory = new SimpleThreadFactory();
490 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
490 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
491          try (PoolCleaner cleaner = cleaner(p)) {
492              p.setThreadFactory(threadFactory);
493              assertSame(threadFactory, p.getThreadFactory());
# Line 460 | Line 498 | public class ScheduledExecutorTest exten
498       * setThreadFactory(null) throws NPE
499       */
500      public void testSetThreadFactoryNull() throws InterruptedException {
501 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
501 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
502          try (PoolCleaner cleaner = cleaner(p)) {
503              try {
504                  p.setThreadFactory(null);
# Line 470 | 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() {
525 <
526 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
527 <        try {
528 <            assertFalse(p.isShutdown());
529 <        }
530 <        finally {
531 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
525 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
526 >        assertFalse(p.isShutdown());
527 >        try (PoolCleaner cleaner = cleaner(p)) {
528 >            try {
529 >                p.shutdown();
530 >                assertTrue(p.isShutdown());
531 >            } catch (SecurityException ok) {}
532          }
484        assertTrue(p.isShutdown());
533      }
534  
535      /**
# Line 497 | Line 545 | public class ScheduledExecutorTest exten
545                  public void realRun() throws InterruptedException {
546                      assertFalse(p.isTerminated());
547                      threadStarted.countDown();
548 <                    done.await();
548 >                    await(done);
549                  }});
550 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
550 >            await(threadStarted);
551              assertFalse(p.isTerminating());
552              done.countDown();
553              try { p.shutdown(); } catch (SecurityException ok) { return; }
# Line 521 | Line 569 | public class ScheduledExecutorTest exten
569                  public void realRun() throws InterruptedException {
570                      assertFalse(p.isTerminating());
571                      threadStarted.countDown();
572 <                    done.await();
572 >                    await(done);
573                  }});
574 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
574 >            await(threadStarted);
575              assertFalse(p.isTerminating());
576              done.countDown();
577              try { p.shutdown(); } catch (SecurityException ok) { return; }
# Line 537 | Line 585 | public class ScheduledExecutorTest exten
585       * getQueue returns the work queue, which contains queued tasks
586       */
587      public void testGetQueue() throws InterruptedException {
588 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
589 <        try (PoolCleaner cleaner = cleaner(p)) {
588 >        final CountDownLatch done = new CountDownLatch(1);
589 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
590 >        try (PoolCleaner cleaner = cleaner(p, done)) {
591              final CountDownLatch threadStarted = new CountDownLatch(1);
543            final CountDownLatch done = new CountDownLatch(1);
592              ScheduledFuture[] tasks = new ScheduledFuture[5];
593              for (int i = 0; i < tasks.length; i++) {
594                  Runnable r = new CheckedRunnable() {
595                      public void realRun() throws InterruptedException {
596                          threadStarted.countDown();
597 <                        done.await();
597 >                        await(done);
598                      }};
599                  tasks[i] = p.schedule(r, 1, MILLISECONDS);
600              }
601 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
601 >            await(threadStarted);
602              BlockingQueue<Runnable> q = p.getQueue();
603              assertTrue(q.contains(tasks[tasks.length - 1]));
604              assertFalse(q.contains(tasks[0]));
557            done.countDown();
605          }
606      }
607  
# Line 562 | Line 609 | public class ScheduledExecutorTest exten
609       * remove(task) removes queued task, and fails to remove active task
610       */
611      public void testRemove() throws InterruptedException {
612 +        final CountDownLatch done = new CountDownLatch(1);
613          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
614 <        try (PoolCleaner cleaner = cleaner(p)) {
614 >        try (PoolCleaner cleaner = cleaner(p, done)) {
615              ScheduledFuture[] tasks = new ScheduledFuture[5];
616              final CountDownLatch threadStarted = new CountDownLatch(1);
569            final CountDownLatch done = new CountDownLatch(1);
617              for (int i = 0; i < tasks.length; i++) {
618                  Runnable r = new CheckedRunnable() {
619                      public void realRun() throws InterruptedException {
620                          threadStarted.countDown();
621 <                        done.await();
621 >                        await(done);
622                      }};
623                  tasks[i] = p.schedule(r, 1, MILLISECONDS);
624              }
625 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
625 >            await(threadStarted);
626              BlockingQueue<Runnable> q = p.getQueue();
627              assertFalse(p.remove((Runnable)tasks[0]));
628              assertTrue(q.contains((Runnable)tasks[4]));
# Line 586 | Line 633 | public class ScheduledExecutorTest exten
633              assertTrue(q.contains((Runnable)tasks[3]));
634              assertTrue(p.remove((Runnable)tasks[3]));
635              assertFalse(q.contains((Runnable)tasks[3]));
589            done.countDown();
636          }
637      }
638  
# Line 594 | Line 640 | public class ScheduledExecutorTest exten
640       * purge eventually removes cancelled tasks from the queue
641       */
642      public void testPurge() throws InterruptedException {
643 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
644 <        ScheduledFuture[] tasks = new ScheduledFuture[5];
645 <        for (int i = 0; i < tasks.length; i++)
646 <            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
647 <                                  LONG_DELAY_MS, MILLISECONDS);
648 <        try {
643 >        final ScheduledFuture[] tasks = new ScheduledFuture[5];
644 >        final Runnable releaser = new Runnable() { public void run() {
645 >            for (ScheduledFuture task : tasks)
646 >                if (task != null) task.cancel(true); }};
647 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
648 >        try (PoolCleaner cleaner = cleaner(p, releaser)) {
649 >            for (int i = 0; i < tasks.length; i++)
650 >                tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
651 >                                      LONG_DELAY_MS, MILLISECONDS);
652              int max = tasks.length;
653              if (tasks[4].cancel(true)) --max;
654              if (tasks[3].cancel(true)) --max;
# Line 611 | Line 660 | public class ScheduledExecutorTest exten
660                  long count = p.getTaskCount();
661                  if (count == max)
662                      return;
663 <            } while (millisElapsedSince(startTime) < MEDIUM_DELAY_MS);
663 >            } while (millisElapsedSince(startTime) < LONG_DELAY_MS);
664              fail("Purge failed to remove cancelled tasks");
616        } finally {
617            for (ScheduledFuture task : tasks)
618                task.cancel(true);
619            joinPool(p);
665          }
666      }
667  
# Line 630 | Line 675 | public class ScheduledExecutorTest exten
675          final AtomicInteger ran = new AtomicInteger(0);
676          final ScheduledThreadPoolExecutor p =
677              new ScheduledThreadPoolExecutor(poolSize);
678 <        CountDownLatch threadsStarted = new CountDownLatch(poolSize);
678 >        final CountDownLatch threadsStarted = new CountDownLatch(poolSize);
679          Runnable waiter = new CheckedRunnable() { public void realRun() {
680              threadsStarted.countDown();
681              try {
# Line 640 | Line 685 | public class ScheduledExecutorTest exten
685          }};
686          for (int i = 0; i < count; i++)
687              p.execute(waiter);
688 <        assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS));
688 >        await(threadsStarted);
689          assertEquals(poolSize, p.getActiveCount());
690          assertEquals(0, p.getCompletedTaskCount());
691          final List<Runnable> queuedTasks;
# Line 663 | Line 708 | public class ScheduledExecutorTest exten
708       * and those tasks are drained from the queue
709       */
710      public void testShutdownNow_delayedTasks() throws InterruptedException {
711 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
711 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
712          List<ScheduledFuture> tasks = new ArrayList<>();
713          for (int i = 0; i < 3; i++) {
714              Runnable r = new NoOpRunnable();
# Line 700 | Line 745 | public class ScheduledExecutorTest exten
745       * - setContinueExistingPeriodicTasksAfterShutdownPolicy
746       */
747      public void testShutdown_cancellation() throws Exception {
703        Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE };
704        for (Boolean policy : allBooleans)
705    {
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 729 | 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 737 | 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 764 | Line 821 | public class ScheduledExecutorTest exten
821              assertEquals(effectiveDelayedPolicy,
822                           p.getQueue().containsAll(delayeds));
823          }
824 <        // Release all pool threads
768 <        unblock.countDown();
824 >        unblock.countDown();    // Release all pool threads
825  
826 <        for (Future<?> delayed : delayeds) {
827 <            if (effectiveDelayedPolicy) {
772 <                assertNull(delayed.get());
773 <            }
774 <        }
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 855 | 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 872 | 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 889 | 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 927 | 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 943 | 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 962 | 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 991 | 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 1020 | 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 1037 | Line 1100 | public class ScheduledExecutorTest exten
1100      public void testTimedInvokeAny4() throws Exception {
1101          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1102          try (PoolCleaner cleaner = cleaner(e)) {
1103 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1103 >            long startTime = System.nanoTime();
1104 >            List<Callable<String>> l = new ArrayList<>();
1105              l.add(new NPETask());
1106              try {
1107 <                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1107 >                e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1108                  shouldThrow();
1109              } catch (ExecutionException success) {
1110                  assertTrue(success.getCause() instanceof NullPointerException);
1111              }
1112 +            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1113          }
1114      }
1115  
# Line 1054 | Line 1119 | public class ScheduledExecutorTest exten
1119      public void testTimedInvokeAny5() throws Exception {
1120          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1121          try (PoolCleaner cleaner = cleaner(e)) {
1122 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1122 >            long startTime = System.nanoTime();
1123 >            List<Callable<String>> l = new ArrayList<>();
1124              l.add(new StringTask());
1125              l.add(new StringTask());
1126 <            String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1126 >            String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1127              assertSame(TEST_STRING, result);
1128 +            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1129          }
1130      }
1131  
# Line 1081 | 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 1108 | 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 1124 | 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, MEDIUM_DELAY_MS, MILLISECONDS);
1197 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1198              assertEquals(1, futures.size());
1199              try {
1200                  futures.get(0).get();
# Line 1144 | 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 1159 | Line 1226 | public class ScheduledExecutorTest exten
1226       * timed invokeAll(c) cancels tasks not completed by timeout
1227       */
1228      public void testTimedInvokeAll6() throws Exception {
1229 <        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1230 <        try (PoolCleaner cleaner = cleaner(e)) {
1231 <            for (long timeout = timeoutMillis();;) {
1229 >        for (long timeout = timeoutMillis();;) {
1230 >            final CountDownLatch done = new CountDownLatch(1);
1231 >            final Callable<String> waiter = new CheckedCallable<String>() {
1232 >                public String realCall() {
1233 >                    try { done.await(LONG_DELAY_MS, MILLISECONDS); }
1234 >                    catch (InterruptedException ok) {}
1235 >                    return "1"; }};
1236 >            final ExecutorService p = new ScheduledThreadPoolExecutor(2);
1237 >            try (PoolCleaner cleaner = cleaner(p, done)) {
1238                  List<Callable<String>> tasks = new ArrayList<>();
1239                  tasks.add(new StringTask("0"));
1240 <                tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1240 >                tasks.add(waiter);
1241                  tasks.add(new StringTask("2"));
1242                  long startTime = System.nanoTime();
1243                  List<Future<String>> futures =
1244 <                    e.invokeAll(tasks, timeout, MILLISECONDS);
1244 >                    p.invokeAll(tasks, timeout, MILLISECONDS);
1245                  assertEquals(tasks.size(), futures.size());
1246                  assertTrue(millisElapsedSince(startTime) >= timeout);
1247                  for (Future future : futures)
# Line 1187 | 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