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.73 by jsr166, Tue Oct 6 06:02:53 2015 UTC vs.
Revision 1.96 by jsr166, Mon Jan 8 02:04:15 2018 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;
14 + import java.util.Collection;
15 + import java.util.Collections;
16   import java.util.HashSet;
17   import java.util.List;
18   import java.util.concurrent.BlockingQueue;
# Line 17 | Line 20 | import java.util.concurrent.Callable;
20   import java.util.concurrent.CancellationException;
21   import java.util.concurrent.CountDownLatch;
22   import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.Executors;
23   import java.util.concurrent.ExecutorService;
24   import java.util.concurrent.Future;
25   import java.util.concurrent.RejectedExecutionException;
26   import java.util.concurrent.ScheduledFuture;
27   import java.util.concurrent.ScheduledThreadPoolExecutor;
28   import java.util.concurrent.ThreadFactory;
29 + import java.util.concurrent.ThreadLocalRandom;
30   import java.util.concurrent.ThreadPoolExecutor;
31 + import java.util.concurrent.atomic.AtomicBoolean;
32   import java.util.concurrent.atomic.AtomicInteger;
33 + import java.util.concurrent.atomic.AtomicLong;
34 + import java.util.stream.Stream;
35  
36   import junit.framework.Test;
37   import junit.framework.TestSuite;
# Line 48 | Line 54 | public class ScheduledExecutorTest exten
54              final Runnable task = new CheckedRunnable() {
55                  public void realRun() { done.countDown(); }};
56              p.execute(task);
57 <            assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
57 >            await(done);
58          }
59      }
60  
# Line 69 | Line 75 | public class ScheduledExecutorTest exten
75              Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
76              assertSame(Boolean.TRUE, f.get());
77              assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
78 <            assertTrue(done.await(0L, MILLISECONDS));
78 >            assertEquals(0L, done.getCount());
79          }
80      }
81  
# Line 143 | Line 149 | public class ScheduledExecutorTest exten
149      }
150  
151      /**
152 <     * scheduleAtFixedRate executes series of tasks at given rate
152 >     * scheduleAtFixedRate executes series of tasks at given rate.
153 >     * Eventually, it must hold that:
154 >     *   cycles - 1 <= elapsedMillis/delay < cycles
155       */
156      public void testFixedRateSequence() throws InterruptedException {
157          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
158          try (PoolCleaner cleaner = cleaner(p)) {
159              for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
160 <                long startTime = System.nanoTime();
161 <                int cycles = 10;
160 >                final long startTime = System.nanoTime();
161 >                final int cycles = 8;
162                  final CountDownLatch done = new CountDownLatch(cycles);
163 <                Runnable task = new CheckedRunnable() {
163 >                final Runnable task = new CheckedRunnable() {
164                      public void realRun() { done.countDown(); }};
165 <                ScheduledFuture h =
165 >                final ScheduledFuture periodicTask =
166                      p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
167 <                await(done);
168 <                h.cancel(true);
169 <                double normalizedTime =
170 <                    (double) millisElapsedSince(startTime) / delay;
171 <                if (normalizedTime >= cycles - 1 &&
172 <                    normalizedTime <= cycles)
167 >                final int totalDelayMillis = (cycles - 1) * delay;
168 >                await(done, totalDelayMillis + LONG_DELAY_MS);
169 >                periodicTask.cancel(true);
170 >                final long elapsedMillis = millisElapsedSince(startTime);
171 >                assertTrue(elapsedMillis >= totalDelayMillis);
172 >                if (elapsedMillis <= cycles * delay)
173                      return;
174 +                // else retry with longer delay
175              }
176 <            throw new AssertionError("unexpected execution rate");
176 >            fail("unexpected execution rate");
177          }
178      }
179  
180      /**
181 <     * scheduleWithFixedDelay executes series of tasks with given period
181 >     * scheduleWithFixedDelay executes series of tasks with given period.
182 >     * Eventually, it must hold that each task starts at least delay and at
183 >     * most 2 * delay after the termination of the previous task.
184       */
185      public void testFixedDelaySequence() throws InterruptedException {
186          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
187          try (PoolCleaner cleaner = cleaner(p)) {
188              for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
189 <                long startTime = System.nanoTime();
190 <                int cycles = 10;
189 >                final long startTime = System.nanoTime();
190 >                final AtomicLong previous = new AtomicLong(startTime);
191 >                final AtomicBoolean tryLongerDelay = new AtomicBoolean(false);
192 >                final int cycles = 8;
193                  final CountDownLatch done = new CountDownLatch(cycles);
194 <                Runnable task = new CheckedRunnable() {
195 <                    public void realRun() { done.countDown(); }};
196 <                ScheduledFuture h =
194 >                final int d = delay;
195 >                final Runnable task = new CheckedRunnable() {
196 >                    public void realRun() {
197 >                        long now = System.nanoTime();
198 >                        long elapsedMillis
199 >                            = NANOSECONDS.toMillis(now - previous.get());
200 >                        if (done.getCount() == cycles) { // first execution
201 >                            if (elapsedMillis >= d)
202 >                                tryLongerDelay.set(true);
203 >                        } else {
204 >                            assertTrue(elapsedMillis >= d);
205 >                            if (elapsedMillis >= 2 * d)
206 >                                tryLongerDelay.set(true);
207 >                        }
208 >                        previous.set(now);
209 >                        done.countDown();
210 >                    }};
211 >                final ScheduledFuture periodicTask =
212                      p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
213 <                await(done);
214 <                h.cancel(true);
215 <                double normalizedTime =
216 <                    (double) millisElapsedSince(startTime) / delay;
217 <                if (normalizedTime >= cycles - 1 &&
218 <                    normalizedTime <= cycles)
213 >                final int totalDelayMillis = (cycles - 1) * delay;
214 >                await(done, totalDelayMillis + cycles * LONG_DELAY_MS);
215 >                periodicTask.cancel(true);
216 >                final long elapsedMillis = millisElapsedSince(startTime);
217 >                assertTrue(elapsedMillis >= totalDelayMillis);
218 >                if (!tryLongerDelay.get())
219                      return;
220 +                // else retry with longer delay
221              }
222 <            throw new AssertionError("unexpected execution rate");
222 >            fail("unexpected execution rate");
223          }
224      }
225  
226      /**
227 <     * execute(null) throws NPE
227 >     * Submitting null tasks throws NullPointerException
228       */
229 <    public void testExecuteNull() throws InterruptedException {
229 >    public void testNullTaskSubmission() {
230          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
231          try (PoolCleaner cleaner = cleaner(p)) {
232 <            try {
204 <                p.execute(null);
205 <                shouldThrow();
206 <            } catch (NullPointerException success) {}
232 >            assertNullTaskSubmissionThrowsNullPointerException(p);
233          }
234      }
235  
236      /**
237 <     * schedule(null) throws NPE
237 >     * Submitted tasks are rejected when shutdown
238       */
239 <    public void testScheduleNull() throws InterruptedException {
239 >    public void testSubmittedTasksRejectedWhenShutdown() throws InterruptedException {
240          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
241 <        try (PoolCleaner cleaner = cleaner(p)) {
242 <            try {
243 <                TrackedCallable callable = null;
244 <                Future f = p.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
245 <                shouldThrow();
246 <            } catch (NullPointerException success) {}
247 <        }
248 <    }
241 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
242 >        final CountDownLatch threadsStarted = new CountDownLatch(p.getCorePoolSize());
243 >        final CountDownLatch done = new CountDownLatch(1);
244 >        final Runnable r = () -> {
245 >            threadsStarted.countDown();
246 >            for (;;) {
247 >                try {
248 >                    done.await();
249 >                    return;
250 >                } catch (InterruptedException shutdownNowDeliberatelyIgnored) {}
251 >            }};
252 >        final Callable<Boolean> c = () -> {
253 >            threadsStarted.countDown();
254 >            for (;;) {
255 >                try {
256 >                    done.await();
257 >                    return Boolean.TRUE;
258 >                } catch (InterruptedException shutdownNowDeliberatelyIgnored) {}
259 >            }};
260  
261 <    /**
262 <     * execute throws RejectedExecutionException if shutdown
263 <     */
264 <    public void testSchedule1_RejectedExecutionException() throws InterruptedException {
265 <        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
266 <        try (PoolCleaner cleaner = cleaner(p)) {
267 <            try {
268 <                p.shutdown();
269 <                p.schedule(new NoOpRunnable(),
233 <                           MEDIUM_DELAY_MS, MILLISECONDS);
234 <                shouldThrow();
235 <            } catch (RejectedExecutionException success) {
236 <            } catch (SecurityException ok) {}
237 <        }
238 <    }
261 >        try (PoolCleaner cleaner = cleaner(p, done)) {
262 >            for (int i = p.getCorePoolSize(); i--> 0; ) {
263 >                switch (rnd.nextInt(4)) {
264 >                case 0: p.execute(r); break;
265 >                case 1: assertFalse(p.submit(r).isDone()); break;
266 >                case 2: assertFalse(p.submit(r, Boolean.TRUE).isDone()); break;
267 >                case 3: assertFalse(p.submit(c).isDone()); break;
268 >                }
269 >            }
270  
271 <    /**
272 <     * schedule throws RejectedExecutionException if shutdown
242 <     */
243 <    public void testSchedule2_RejectedExecutionException() throws InterruptedException {
244 <        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
245 <        try (PoolCleaner cleaner = cleaner(p)) {
246 <            try {
247 <                p.shutdown();
248 <                p.schedule(new NoOpCallable(),
249 <                           MEDIUM_DELAY_MS, MILLISECONDS);
250 <                shouldThrow();
251 <            } catch (RejectedExecutionException success) {
252 <            } catch (SecurityException ok) {}
253 <        }
254 <    }
271 >            // ScheduledThreadPoolExecutor has an unbounded queue, so never saturated.
272 >            await(threadsStarted);
273  
274 <    /**
275 <     * schedule callable throws RejectedExecutionException if shutdown
276 <     */
259 <    public void testSchedule3_RejectedExecutionException() throws InterruptedException {
260 <        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
261 <        try (PoolCleaner cleaner = cleaner(p)) {
262 <            try {
274 >            if (rnd.nextBoolean())
275 >                p.shutdownNow();
276 >            else
277                  p.shutdown();
278 <                p.schedule(new NoOpCallable(),
279 <                           MEDIUM_DELAY_MS, MILLISECONDS);
280 <                shouldThrow();
267 <            } catch (RejectedExecutionException success) {
268 <            } catch (SecurityException ok) {}
269 <        }
270 <    }
278 >            // Pool is shutdown, but not yet terminated
279 >            assertTaskSubmissionsAreRejected(p);
280 >            assertFalse(p.isTerminated());
281  
282 <    /**
283 <     * scheduleAtFixedRate throws RejectedExecutionException if shutdown
274 <     */
275 <    public void testScheduleAtFixedRate1_RejectedExecutionException() throws InterruptedException {
276 <        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
277 <        try (PoolCleaner cleaner = cleaner(p)) {
278 <            try {
279 <                p.shutdown();
280 <                p.scheduleAtFixedRate(new NoOpRunnable(),
281 <                                      MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
282 <                shouldThrow();
283 <            } catch (RejectedExecutionException success) {
284 <            } catch (SecurityException ok) {}
285 <        }
286 <    }
282 >            done.countDown();   // release blocking tasks
283 >            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
284  
285 <    /**
289 <     * scheduleWithFixedDelay throws RejectedExecutionException if shutdown
290 <     */
291 <    public void testScheduleWithFixedDelay1_RejectedExecutionException() throws InterruptedException {
292 <        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
293 <        try (PoolCleaner cleaner = cleaner(p)) {
294 <            try {
295 <                p.shutdown();
296 <                p.scheduleWithFixedDelay(new NoOpRunnable(),
297 <                                         MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
298 <                shouldThrow();
299 <            } catch (RejectedExecutionException success) {
300 <            } catch (SecurityException ok) {}
285 >            assertTaskSubmissionsAreRejected(p);
286          }
287 +        assertEquals(p.getCorePoolSize(), p.getCompletedTaskCount());
288      }
289  
290      /**
# Line 337 | Line 323 | public class ScheduledExecutorTest exten
323                  public void realRun() throws InterruptedException {
324                      threadStarted.countDown();
325                      assertEquals(0, p.getCompletedTaskCount());
326 <                    threadProceed.await();
326 >                    await(threadProceed);
327                      threadDone.countDown();
328                  }});
329              await(threadStarted);
330              assertEquals(0, p.getCompletedTaskCount());
331              threadProceed.countDown();
332 <            threadDone.await();
332 >            await(threadDone);
333              long startTime = System.nanoTime();
334              while (p.getCompletedTaskCount() != 1) {
335                  if (millisElapsedSince(startTime) > LONG_DELAY_MS)
# Line 482 | Line 468 | public class ScheduledExecutorTest exten
468      }
469  
470      /**
471 +     * The default rejected execution handler is AbortPolicy.
472 +     */
473 +    public void testDefaultRejectedExecutionHandler() {
474 +        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
475 +        try (PoolCleaner cleaner = cleaner(p)) {
476 +            assertTrue(p.getRejectedExecutionHandler()
477 +                       instanceof ThreadPoolExecutor.AbortPolicy);
478 +        }
479 +    }
480 +
481 +    /**
482       * isShutdown is false before shutdown, true after
483       */
484      public void testIsShutdown() {
488
485          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
486 <        try {
487 <            assertFalse(p.isShutdown());
488 <        }
489 <        finally {
490 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
486 >        assertFalse(p.isShutdown());
487 >        try (PoolCleaner cleaner = cleaner(p)) {
488 >            try {
489 >                p.shutdown();
490 >                assertTrue(p.isShutdown());
491 >            } catch (SecurityException ok) {}
492          }
496        assertTrue(p.isShutdown());
493      }
494  
495      /**
# Line 708 | Line 704 | public class ScheduledExecutorTest exten
704       * - setExecuteExistingDelayedTasksAfterShutdownPolicy
705       * - setContinueExistingPeriodicTasksAfterShutdownPolicy
706       */
707 +    @SuppressWarnings("FutureReturnValueIgnored")
708      public void testShutdown_cancellation() throws Exception {
709 <        Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE };
713 <        for (Boolean policy : allBooleans)
714 <    {
715 <        final int poolSize = 2;
709 >        final int poolSize = 4;
710          final ScheduledThreadPoolExecutor p
711              = new ScheduledThreadPoolExecutor(poolSize);
712 <        final boolean effectiveDelayedPolicy = (policy != Boolean.FALSE);
713 <        final boolean effectivePeriodicPolicy = (policy == Boolean.TRUE);
714 <        final boolean effectiveRemovePolicy = (policy == Boolean.TRUE);
715 <        if (policy != null) {
716 <            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(policy);
717 <            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(policy);
718 <            p.setRemoveOnCancelPolicy(policy);
719 <        }
712 >        final BlockingQueue<Runnable> q = p.getQueue();
713 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
714 >        final long delay = rnd.nextInt(2);
715 >        final int rounds = rnd.nextInt(1, 3);
716 >        final boolean effectiveDelayedPolicy;
717 >        final boolean effectivePeriodicPolicy;
718 >        final boolean effectiveRemovePolicy;
719 >
720 >        if (rnd.nextBoolean())
721 >            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(
722 >                effectiveDelayedPolicy = rnd.nextBoolean());
723 >        else
724 >            effectiveDelayedPolicy = true;
725          assertEquals(effectiveDelayedPolicy,
726                       p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
727 +
728 +        if (rnd.nextBoolean())
729 +            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(
730 +                effectivePeriodicPolicy = rnd.nextBoolean());
731 +        else
732 +            effectivePeriodicPolicy = false;
733          assertEquals(effectivePeriodicPolicy,
734                       p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
735 +
736 +        if (rnd.nextBoolean())
737 +            p.setRemoveOnCancelPolicy(
738 +                effectiveRemovePolicy = rnd.nextBoolean());
739 +        else
740 +            effectiveRemovePolicy = false;
741          assertEquals(effectiveRemovePolicy,
742                       p.getRemoveOnCancelPolicy());
743 <        // Strategy: Wedge the pool with poolSize "blocker" threads
743 >
744 >        final boolean periodicTasksContinue = effectivePeriodicPolicy && rnd.nextBoolean();
745 >
746 >        // Strategy: Wedge the pool with one wave of "blocker" tasks,
747 >        // then add a second wave that waits in the queue until unblocked.
748          final AtomicInteger ran = new AtomicInteger(0);
749          final CountDownLatch poolBlocked = new CountDownLatch(poolSize);
750          final CountDownLatch unblock = new CountDownLatch(1);
751 <        final CountDownLatch periodicLatch1 = new CountDownLatch(2);
737 <        final CountDownLatch periodicLatch2 = new CountDownLatch(2);
738 <        Runnable task = new CheckedRunnable() { public void realRun()
739 <                                                    throws InterruptedException {
740 <            poolBlocked.countDown();
741 <            assertTrue(unblock.await(LONG_DELAY_MS, MILLISECONDS));
742 <            ran.getAndIncrement();
743 <        }};
744 <        List<Future<?>> blockers = new ArrayList<>();
745 <        List<Future<?>> periodics = new ArrayList<>();
746 <        List<Future<?>> delayeds = new ArrayList<>();
747 <        for (int i = 0; i < poolSize; i++)
748 <            blockers.add(p.submit(task));
749 <        assertTrue(poolBlocked.await(LONG_DELAY_MS, MILLISECONDS));
750 <
751 <        periodics.add(p.scheduleAtFixedRate(countDowner(periodicLatch1),
752 <                                            1, 1, MILLISECONDS));
753 <        periodics.add(p.scheduleWithFixedDelay(countDowner(periodicLatch2),
754 <                                               1, 1, MILLISECONDS));
755 <        delayeds.add(p.schedule(task, 1, MILLISECONDS));
751 >        final RuntimeException exception = new RuntimeException();
752  
753 <        assertTrue(p.getQueue().containsAll(periodics));
754 <        assertTrue(p.getQueue().containsAll(delayeds));
755 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
756 <        assertTrue(p.isShutdown());
757 <        assertFalse(p.isTerminated());
758 <        for (Future<?> periodic : periodics) {
759 <            assertTrue(effectivePeriodicPolicy ^ periodic.isCancelled());
764 <            assertTrue(effectivePeriodicPolicy ^ periodic.isDone());
765 <        }
766 <        for (Future<?> delayed : delayeds) {
767 <            assertTrue(effectiveDelayedPolicy ^ delayed.isCancelled());
768 <            assertTrue(effectiveDelayedPolicy ^ delayed.isDone());
769 <        }
770 <        if (testImplementationDetails) {
771 <            assertEquals(effectivePeriodicPolicy,
772 <                         p.getQueue().containsAll(periodics));
773 <            assertEquals(effectiveDelayedPolicy,
774 <                         p.getQueue().containsAll(delayeds));
775 <        }
776 <        // Release all pool threads
777 <        unblock.countDown();
778 <
779 <        for (Future<?> delayed : delayeds) {
780 <            if (effectiveDelayedPolicy) {
781 <                assertNull(delayed.get());
753 >        class Task implements Runnable {
754 >            public void run() {
755 >                try {
756 >                    ran.getAndIncrement();
757 >                    poolBlocked.countDown();
758 >                    await(unblock);
759 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
760              }
761          }
762 <        if (effectivePeriodicPolicy) {
763 <            assertTrue(periodicLatch1.await(LONG_DELAY_MS, MILLISECONDS));
764 <            assertTrue(periodicLatch2.await(LONG_DELAY_MS, MILLISECONDS));
765 <            for (Future<?> periodic : periodics) {
766 <                assertTrue(periodic.cancel(false));
767 <                assertTrue(periodic.isCancelled());
768 <                assertTrue(periodic.isDone());
762 >
763 >        class PeriodicTask extends Task {
764 >            PeriodicTask(int rounds) { this.rounds = rounds; }
765 >            int rounds;
766 >            public void run() {
767 >                if (--rounds == 0) super.run();
768 >                // throw exception to surely terminate this periodic task,
769 >                // but in a separate execution and in a detectable way.
770 >                if (rounds == -1) throw exception;
771              }
772          }
773 +
774 +        Runnable task = new Task();
775 +
776 +        List<Future<?>> immediates = new ArrayList<>();
777 +        List<Future<?>> delayeds   = new ArrayList<>();
778 +        List<Future<?>> periodics  = new ArrayList<>();
779 +
780 +        immediates.add(p.submit(task));
781 +        delayeds.add(p.schedule(task, delay, MILLISECONDS));
782 +        periodics.add(p.scheduleAtFixedRate(
783 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
784 +        periodics.add(p.scheduleWithFixedDelay(
785 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
786 +
787 +        await(poolBlocked);
788 +
789 +        assertEquals(poolSize, ran.get());
790 +        assertEquals(poolSize, p.getActiveCount());
791 +        assertTrue(q.isEmpty());
792 +
793 +        // Add second wave of tasks.
794 +        immediates.add(p.submit(task));
795 +        delayeds.add(p.schedule(task, effectiveDelayedPolicy ? delay : LONG_DELAY_MS, MILLISECONDS));
796 +        periodics.add(p.scheduleAtFixedRate(
797 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
798 +        periodics.add(p.scheduleWithFixedDelay(
799 +                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
800 +
801 +        assertEquals(poolSize, q.size());
802 +        assertEquals(poolSize, ran.get());
803 +
804 +        immediates.forEach(
805 +            f -> assertTrue(((ScheduledFuture)f).getDelay(NANOSECONDS) <= 0L));
806 +
807 +        Stream.of(immediates, delayeds, periodics).flatMap(Collection::stream)
808 +            .forEach(f -> assertFalse(f.isDone()));
809 +
810 +        try { p.shutdown(); } catch (SecurityException ok) { return; }
811 +        assertTrue(p.isShutdown());
812 +        assertTrue(p.isTerminating());
813 +        assertFalse(p.isTerminated());
814 +
815 +        if (rnd.nextBoolean())
816 +            assertThrows(
817 +                RejectedExecutionException.class,
818 +                () -> p.submit(task),
819 +                () -> p.schedule(task, 1, SECONDS),
820 +                () -> p.scheduleAtFixedRate(
821 +                    new PeriodicTask(1), 1, 1, SECONDS),
822 +                () -> p.scheduleWithFixedDelay(
823 +                    new PeriodicTask(2), 1, 1, SECONDS));
824 +
825 +        assertTrue(q.contains(immediates.get(1)));
826 +        assertTrue(!effectiveDelayedPolicy
827 +                   ^ q.contains(delayeds.get(1)));
828 +        assertTrue(!effectivePeriodicPolicy
829 +                   ^ q.containsAll(periodics.subList(2, 4)));
830 +
831 +        immediates.forEach(f -> assertFalse(f.isDone()));
832 +
833 +        assertFalse(delayeds.get(0).isDone());
834 +        if (effectiveDelayedPolicy)
835 +            assertFalse(delayeds.get(1).isDone());
836 +        else
837 +            assertTrue(delayeds.get(1).isCancelled());
838 +
839 +        if (effectivePeriodicPolicy)
840 +            periodics.forEach(
841 +                f -> {
842 +                    assertFalse(f.isDone());
843 +                    if (!periodicTasksContinue) {
844 +                        assertTrue(f.cancel(false));
845 +                        assertTrue(f.isCancelled());
846 +                    }
847 +                });
848 +        else {
849 +            periodics.subList(0, 2).forEach(f -> assertFalse(f.isDone()));
850 +            periodics.subList(2, 4).forEach(f -> assertTrue(f.isCancelled()));
851 +        }
852 +
853 +        unblock.countDown();    // Release all pool threads
854 +
855          assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
856 +        assertFalse(p.isTerminating());
857          assertTrue(p.isTerminated());
858 <        assertEquals(2 + (effectiveDelayedPolicy ? 1 : 0), ran.get());
859 <    }}
858 >
859 >        assertTrue(q.isEmpty());
860 >
861 >        Stream.of(immediates, delayeds, periodics).flatMap(Collection::stream)
862 >            .forEach(f -> assertTrue(f.isDone()));
863 >
864 >        for (Future<?> f : immediates) assertNull(f.get());
865 >
866 >        assertNull(delayeds.get(0).get());
867 >        if (effectiveDelayedPolicy)
868 >            assertNull(delayeds.get(1).get());
869 >        else
870 >            assertTrue(delayeds.get(1).isCancelled());
871 >
872 >        if (periodicTasksContinue)
873 >            periodics.forEach(
874 >                f -> {
875 >                    try { f.get(); }
876 >                    catch (ExecutionException success) {
877 >                        assertSame(exception, success.getCause());
878 >                    }
879 >                    catch (Throwable fail) { threadUnexpectedException(fail); }
880 >                });
881 >        else
882 >            periodics.forEach(f -> assertTrue(f.isCancelled()));
883 >
884 >        assertEquals(poolSize + 1
885 >                     + (effectiveDelayedPolicy ? 1 : 0)
886 >                     + (periodicTasksContinue ? 2 : 0),
887 >                     ran.get());
888 >    }
889  
890      /**
891       * completed submit of callable returns result
# Line 832 | Line 924 | public class ScheduledExecutorTest exten
924      }
925  
926      /**
927 <     * invokeAny(null) throws NPE
927 >     * invokeAny(null) throws NullPointerException
928       */
929      public void testInvokeAny1() throws Exception {
930          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
# Line 845 | Line 937 | public class ScheduledExecutorTest exten
937      }
938  
939      /**
940 <     * invokeAny(empty collection) throws IAE
940 >     * invokeAny(empty collection) throws IllegalArgumentException
941       */
942      public void testInvokeAny2() throws Exception {
943          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
# Line 858 | Line 950 | public class ScheduledExecutorTest exten
950      }
951  
952      /**
953 <     * invokeAny(c) throws NPE if c has null elements
953 >     * invokeAny(c) throws NullPointerException if c has null elements
954       */
955      public void testInvokeAny3() throws Exception {
956          CountDownLatch latch = new CountDownLatch(1);
957          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
958          try (PoolCleaner cleaner = cleaner(e)) {
959 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
959 >            List<Callable<String>> l = new ArrayList<>();
960              l.add(latchAwaitingStringTask(latch));
961              l.add(null);
962              try {
# Line 881 | Line 973 | public class ScheduledExecutorTest exten
973      public void testInvokeAny4() throws Exception {
974          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
975          try (PoolCleaner cleaner = cleaner(e)) {
976 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
976 >            List<Callable<String>> l = new ArrayList<>();
977              l.add(new NPETask());
978              try {
979                  e.invokeAny(l);
# Line 898 | Line 990 | public class ScheduledExecutorTest exten
990      public void testInvokeAny5() 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(new StringTask());
996              String result = e.invokeAny(l);
# Line 920 | Line 1012 | public class ScheduledExecutorTest exten
1012      }
1013  
1014      /**
1015 <     * invokeAll(empty collection) returns empty collection
1015 >     * invokeAll(empty collection) returns empty list
1016       */
1017      public void testInvokeAll2() throws Exception {
1018          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1019 +        final Collection<Callable<String>> emptyCollection
1020 +            = Collections.emptyList();
1021          try (PoolCleaner cleaner = cleaner(e)) {
1022 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
1022 >            List<Future<String>> r = e.invokeAll(emptyCollection);
1023              assertTrue(r.isEmpty());
1024          }
1025      }
# Line 936 | Line 1030 | public class ScheduledExecutorTest exten
1030      public void testInvokeAll3() 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(null);
1036              try {
# Line 952 | Line 1046 | public class ScheduledExecutorTest exten
1046      public void testInvokeAll4() throws Exception {
1047          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1048          try (PoolCleaner cleaner = cleaner(e)) {
1049 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1049 >            List<Callable<String>> l = new ArrayList<>();
1050              l.add(new NPETask());
1051              List<Future<String>> futures = e.invokeAll(l);
1052              assertEquals(1, futures.size());
# Line 971 | Line 1065 | public class ScheduledExecutorTest exten
1065      public void testInvokeAll5() throws Exception {
1066          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1067          try (PoolCleaner cleaner = cleaner(e)) {
1068 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1068 >            List<Callable<String>> l = new ArrayList<>();
1069              l.add(new StringTask());
1070              l.add(new StringTask());
1071              List<Future<String>> futures = e.invokeAll(l);
# Line 988 | Line 1082 | public class ScheduledExecutorTest exten
1082          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1083          try (PoolCleaner cleaner = cleaner(e)) {
1084              try {
1085 <                e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1085 >                e.invokeAny(null, randomTimeout(), randomTimeUnit());
1086                  shouldThrow();
1087              } catch (NullPointerException success) {}
1088          }
1089      }
1090  
1091      /**
1092 <     * timed invokeAny(,,null) throws NPE
1092 >     * timed invokeAny(,,null) throws NullPointerException
1093       */
1094      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1095          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1096          try (PoolCleaner cleaner = cleaner(e)) {
1097 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1097 >            List<Callable<String>> l = new ArrayList<>();
1098              l.add(new StringTask());
1099              try {
1100 <                e.invokeAny(l, MEDIUM_DELAY_MS, null);
1100 >                e.invokeAny(l, randomTimeout(), null);
1101                  shouldThrow();
1102              } catch (NullPointerException success) {}
1103          }
1104      }
1105  
1106      /**
1107 <     * timed invokeAny(empty collection) throws IAE
1107 >     * timed invokeAny(empty collection) throws IllegalArgumentException
1108       */
1109      public void testTimedInvokeAny2() throws Exception {
1110          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1111 +        final Collection<Callable<String>> emptyCollection
1112 +            = Collections.emptyList();
1113          try (PoolCleaner cleaner = cleaner(e)) {
1114              try {
1115 <                e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1115 >                e.invokeAny(emptyCollection, randomTimeout(), randomTimeUnit());
1116                  shouldThrow();
1117              } catch (IllegalArgumentException success) {}
1118          }
# Line 1029 | Line 1125 | public class ScheduledExecutorTest exten
1125          CountDownLatch latch = new CountDownLatch(1);
1126          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1127          try (PoolCleaner cleaner = cleaner(e)) {
1128 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1128 >            List<Callable<String>> l = new ArrayList<>();
1129              l.add(latchAwaitingStringTask(latch));
1130              l.add(null);
1131              try {
1132 <                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1132 >                e.invokeAny(l, randomTimeout(), randomTimeUnit());
1133                  shouldThrow();
1134              } catch (NullPointerException success) {}
1135              latch.countDown();
# Line 1046 | Line 1142 | public class ScheduledExecutorTest exten
1142      public void testTimedInvokeAny4() throws Exception {
1143          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1144          try (PoolCleaner cleaner = cleaner(e)) {
1145 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1145 >            long startTime = System.nanoTime();
1146 >            List<Callable<String>> l = new ArrayList<>();
1147              l.add(new NPETask());
1148              try {
1149 <                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1149 >                e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1150                  shouldThrow();
1151              } catch (ExecutionException success) {
1152                  assertTrue(success.getCause() instanceof NullPointerException);
1153              }
1154 +            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1155          }
1156      }
1157  
# Line 1063 | Line 1161 | public class ScheduledExecutorTest exten
1161      public void testTimedInvokeAny5() throws Exception {
1162          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1163          try (PoolCleaner cleaner = cleaner(e)) {
1164 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1164 >            long startTime = System.nanoTime();
1165 >            List<Callable<String>> l = new ArrayList<>();
1166              l.add(new StringTask());
1167              l.add(new StringTask());
1168 <            String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1168 >            String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1169              assertSame(TEST_STRING, result);
1170 +            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1171          }
1172      }
1173  
# Line 1078 | Line 1178 | public class ScheduledExecutorTest exten
1178          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1179          try (PoolCleaner cleaner = cleaner(e)) {
1180              try {
1181 <                e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1181 >                e.invokeAll(null, randomTimeout(), randomTimeUnit());
1182                  shouldThrow();
1183              } catch (NullPointerException success) {}
1184          }
# Line 1090 | Line 1190 | public class ScheduledExecutorTest exten
1190      public void testTimedInvokeAllNullTimeUnit() throws Exception {
1191          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1192          try (PoolCleaner cleaner = cleaner(e)) {
1193 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1193 >            List<Callable<String>> l = new ArrayList<>();
1194              l.add(new StringTask());
1195              try {
1196 <                e.invokeAll(l, MEDIUM_DELAY_MS, null);
1196 >                e.invokeAll(l, randomTimeout(), null);
1197                  shouldThrow();
1198              } catch (NullPointerException success) {}
1199          }
1200      }
1201  
1202      /**
1203 <     * timed invokeAll(empty collection) returns empty collection
1203 >     * timed invokeAll(empty collection) returns empty list
1204       */
1205      public void testTimedInvokeAll2() throws Exception {
1206          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1207 +        final Collection<Callable<String>> emptyCollection
1208 +            = Collections.emptyList();
1209          try (PoolCleaner cleaner = cleaner(e)) {
1210 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(),
1211 <                                                 MEDIUM_DELAY_MS, MILLISECONDS);
1210 >            List<Future<String>> r =
1211 >                e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit());
1212              assertTrue(r.isEmpty());
1213          }
1214      }
# Line 1117 | Line 1219 | public class ScheduledExecutorTest exten
1219      public void testTimedInvokeAll3() throws Exception {
1220          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1221          try (PoolCleaner cleaner = cleaner(e)) {
1222 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1222 >            List<Callable<String>> l = new ArrayList<>();
1223              l.add(new StringTask());
1224              l.add(null);
1225              try {
1226 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1226 >                e.invokeAll(l, randomTimeout(), randomTimeUnit());
1227                  shouldThrow();
1228              } catch (NullPointerException success) {}
1229          }
# Line 1133 | Line 1235 | public class ScheduledExecutorTest exten
1235      public void testTimedInvokeAll4() throws Exception {
1236          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1237          try (PoolCleaner cleaner = cleaner(e)) {
1238 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1238 >            List<Callable<String>> l = new ArrayList<>();
1239              l.add(new NPETask());
1240              List<Future<String>> futures =
1241                  e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
# Line 1153 | Line 1255 | public class ScheduledExecutorTest exten
1255      public void testTimedInvokeAll5() throws Exception {
1256          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1257          try (PoolCleaner cleaner = cleaner(e)) {
1258 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1258 >            List<Callable<String>> l = new ArrayList<>();
1259              l.add(new StringTask());
1260              l.add(new StringTask());
1261              List<Future<String>> futures =
# Line 1168 | Line 1270 | public class ScheduledExecutorTest exten
1270       * timed invokeAll(c) cancels tasks not completed by timeout
1271       */
1272      public void testTimedInvokeAll6() throws Exception {
1273 <        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1274 <        try (PoolCleaner cleaner = cleaner(e)) {
1275 <            for (long timeout = timeoutMillis();;) {
1273 >        for (long timeout = timeoutMillis();;) {
1274 >            final CountDownLatch done = new CountDownLatch(1);
1275 >            final Callable<String> waiter = new CheckedCallable<String>() {
1276 >                public String realCall() {
1277 >                    try { done.await(LONG_DELAY_MS, MILLISECONDS); }
1278 >                    catch (InterruptedException ok) {}
1279 >                    return "1"; }};
1280 >            final ExecutorService p = new ScheduledThreadPoolExecutor(2);
1281 >            try (PoolCleaner cleaner = cleaner(p, done)) {
1282                  List<Callable<String>> tasks = new ArrayList<>();
1283                  tasks.add(new StringTask("0"));
1284 <                tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1284 >                tasks.add(waiter);
1285                  tasks.add(new StringTask("2"));
1286                  long startTime = System.nanoTime();
1287                  List<Future<String>> futures =
1288 <                    e.invokeAll(tasks, timeout, MILLISECONDS);
1288 >                    p.invokeAll(tasks, timeout, MILLISECONDS);
1289                  assertEquals(tasks.size(), futures.size());
1290                  assertTrue(millisElapsedSince(startTime) >= timeout);
1291                  for (Future future : futures)
# Line 1196 | Line 1304 | public class ScheduledExecutorTest exten
1304          }
1305      }
1306  
1307 +    /**
1308 +     * A fixed delay task with overflowing period should not prevent a
1309 +     * one-shot task from executing.
1310 +     * https://bugs.openjdk.java.net/browse/JDK-8051859
1311 +     */
1312 +    @SuppressWarnings("FutureReturnValueIgnored")
1313 +    public void testScheduleWithFixedDelay_overflow() throws Exception {
1314 +        final CountDownLatch delayedDone = new CountDownLatch(1);
1315 +        final CountDownLatch immediateDone = new CountDownLatch(1);
1316 +        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
1317 +        try (PoolCleaner cleaner = cleaner(p)) {
1318 +            final Runnable delayed = () -> {
1319 +                delayedDone.countDown();
1320 +                p.submit(() -> immediateDone.countDown());
1321 +            };
1322 +            p.scheduleWithFixedDelay(delayed, 0L, Long.MAX_VALUE, SECONDS);
1323 +            await(delayedDone);
1324 +            await(immediateDone);
1325 +        }
1326 +    }
1327 +
1328   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines