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.86 by jsr166, Sat Mar 25 21:41:10 2017 UTC vs.
Revision 1.99 by dl, Tue Jan 26 13:33:06 2021 UTC

# Line 11 | Line 11 | import static java.util.concurrent.TimeU
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 24 | Line 26 | import java.util.concurrent.RejectedExec
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 62 | Line 66 | public class ScheduledExecutorTest exten
66          try (PoolCleaner cleaner = cleaner(p)) {
67              final long startTime = System.nanoTime();
68              final CountDownLatch done = new CountDownLatch(1);
69 <            Callable task = new CheckedCallable<Boolean>() {
69 >            Callable<Boolean> task = new CheckedCallable<Boolean>() {
70                  public Boolean realCall() {
71                      done.countDown();
72                      assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
73                      return Boolean.TRUE;
74                  }};
75 <            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
75 >            Future<Boolean> 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 88 | Line 92 | public class ScheduledExecutorTest exten
92                      done.countDown();
93                      assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
94                  }};
95 <            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
95 >            Future<?> f = p.schedule(task, timeoutMillis(), MILLISECONDS);
96              await(done);
97              assertNull(f.get(LONG_DELAY_MS, MILLISECONDS));
98              assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
# Line 108 | Line 112 | public class ScheduledExecutorTest exten
112                      done.countDown();
113                      assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
114                  }};
115 <            ScheduledFuture f =
115 >            ScheduledFuture<?> f =
116                  p.scheduleAtFixedRate(task, timeoutMillis(),
117                                        LONG_DELAY_MS, MILLISECONDS);
118              await(done);
# Line 130 | Line 134 | public class ScheduledExecutorTest exten
134                      done.countDown();
135                      assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
136                  }};
137 <            ScheduledFuture f =
137 >            ScheduledFuture<?> f =
138                  p.scheduleWithFixedDelay(task, timeoutMillis(),
139                                           LONG_DELAY_MS, MILLISECONDS);
140              await(done);
# Line 158 | Line 162 | public class ScheduledExecutorTest exten
162                  final CountDownLatch done = new CountDownLatch(cycles);
163                  final Runnable task = new CheckedRunnable() {
164                      public void realRun() { done.countDown(); }};
165 <                final ScheduledFuture periodicTask =
165 >                final ScheduledFuture<?> periodicTask =
166                      p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
167                  final int totalDelayMillis = (cycles - 1) * delay;
168                  await(done, totalDelayMillis + LONG_DELAY_MS);
# Line 204 | Line 208 | public class ScheduledExecutorTest exten
208                          previous.set(now);
209                          done.countDown();
210                      }};
211 <                final ScheduledFuture periodicTask =
211 >                final ScheduledFuture<?> periodicTask =
212                      p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
213                  final int totalDelayMillis = (cycles - 1) * delay;
214                  await(done, totalDelayMillis + cycles * LONG_DELAY_MS);
# Line 220 | Line 224 | public class ScheduledExecutorTest exten
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 {
229 <                p.execute(null);
230 <                shouldThrow();
231 <            } 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(),
258 <                           MEDIUM_DELAY_MS, MILLISECONDS);
259 <                shouldThrow();
260 <            } catch (RejectedExecutionException success) {
261 <            } catch (SecurityException ok) {}
262 <        }
263 <    }
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
267 <     */
268 <    public void testSchedule2_RejectedExecutionException() throws InterruptedException {
269 <        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
270 <        try (PoolCleaner cleaner = cleaner(p)) {
271 <            try {
272 <                p.shutdown();
273 <                p.schedule(new NoOpCallable(),
274 <                           MEDIUM_DELAY_MS, MILLISECONDS);
275 <                shouldThrow();
276 <            } catch (RejectedExecutionException success) {
277 <            } catch (SecurityException ok) {}
278 <        }
279 <    }
271 >            // ScheduledThreadPoolExecutor has an unbounded queue, so never saturated.
272 >            await(threadsStarted);
273  
274 <    /**
275 <     * schedule callable throws RejectedExecutionException if shutdown
276 <     */
284 <    public void testSchedule3_RejectedExecutionException() throws InterruptedException {
285 <        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
286 <        try (PoolCleaner cleaner = cleaner(p)) {
287 <            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();
292 <            } catch (RejectedExecutionException success) {
293 <            } catch (SecurityException ok) {}
294 <        }
295 <    }
278 >            // Pool is shutdown, but not yet terminated
279 >            assertTaskSubmissionsAreRejected(p);
280 >            assertFalse(p.isTerminated());
281  
282 <    /**
283 <     * scheduleAtFixedRate throws RejectedExecutionException if shutdown
299 <     */
300 <    public void testScheduleAtFixedRate1_RejectedExecutionException() throws InterruptedException {
301 <        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
302 <        try (PoolCleaner cleaner = cleaner(p)) {
303 <            try {
304 <                p.shutdown();
305 <                p.scheduleAtFixedRate(new NoOpRunnable(),
306 <                                      MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
307 <                shouldThrow();
308 <            } catch (RejectedExecutionException success) {
309 <            } catch (SecurityException ok) {}
310 <        }
311 <    }
282 >            done.countDown();   // release blocking tasks
283 >            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
284  
285 <    /**
314 <     * scheduleWithFixedDelay throws RejectedExecutionException if shutdown
315 <     */
316 <    public void testScheduleWithFixedDelay1_RejectedExecutionException() throws InterruptedException {
317 <        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
318 <        try (PoolCleaner cleaner = cleaner(p)) {
319 <            try {
320 <                p.shutdown();
321 <                p.scheduleWithFixedDelay(new NoOpRunnable(),
322 <                                         MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
323 <                shouldThrow();
324 <            } catch (RejectedExecutionException success) {
325 <            } catch (SecurityException ok) {}
285 >            assertTaskSubmissionsAreRejected(p);
286          }
287 +        assertEquals(p.getCorePoolSize(), p.getCompletedTaskCount());
288      }
289  
290      /**
# Line 588 | Line 549 | public class ScheduledExecutorTest exten
549          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
550          try (PoolCleaner cleaner = cleaner(p, done)) {
551              final CountDownLatch threadStarted = new CountDownLatch(1);
552 <            ScheduledFuture[] tasks = new ScheduledFuture[5];
552 >            @SuppressWarnings("unchecked")
553 >            ScheduledFuture<?>[] tasks = (ScheduledFuture<?>[])new ScheduledFuture[5];
554              for (int i = 0; i < tasks.length; i++) {
555                  Runnable r = new CheckedRunnable() {
556                      public void realRun() throws InterruptedException {
# Line 611 | Line 573 | public class ScheduledExecutorTest exten
573          final CountDownLatch done = new CountDownLatch(1);
574          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
575          try (PoolCleaner cleaner = cleaner(p, done)) {
576 <            ScheduledFuture[] tasks = new ScheduledFuture[5];
576 >            @SuppressWarnings("unchecked")
577 >            ScheduledFuture<?>[] tasks = (ScheduledFuture<?>[])new ScheduledFuture[5];
578              final CountDownLatch threadStarted = new CountDownLatch(1);
579              for (int i = 0; i < tasks.length; i++) {
580                  Runnable r = new CheckedRunnable() {
# Line 639 | Line 602 | public class ScheduledExecutorTest exten
602       * purge eventually removes cancelled tasks from the queue
603       */
604      public void testPurge() throws InterruptedException {
605 <        final ScheduledFuture[] tasks = new ScheduledFuture[5];
605 >        @SuppressWarnings("unchecked")
606 >        ScheduledFuture<?>[] tasks = (ScheduledFuture<?>[])new ScheduledFuture[5];
607          final Runnable releaser = new Runnable() { public void run() {
608 <            for (ScheduledFuture task : tasks)
608 >            for (ScheduledFuture<?> task : tasks)
609                  if (task != null) task.cancel(true); }};
610          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
611          try (PoolCleaner cleaner = cleaner(p, releaser)) {
612              for (int i = 0; i < tasks.length; i++)
613 <                tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
613 >                tasks[i] = p.schedule(possiblyInterruptedRunnable(SMALL_DELAY_MS),
614                                        LONG_DELAY_MS, MILLISECONDS);
615              int max = tasks.length;
616              if (tasks[4].cancel(true)) --max;
# Line 678 | Line 642 | public class ScheduledExecutorTest exten
642          Runnable waiter = new CheckedRunnable() { public void realRun() {
643              threadsStarted.countDown();
644              try {
645 <                MILLISECONDS.sleep(2 * LONG_DELAY_MS);
645 >                MILLISECONDS.sleep(LONGER_DELAY_MS);
646              } catch (InterruptedException success) {}
647              ran.getAndIncrement();
648          }};
# Line 708 | Line 672 | public class ScheduledExecutorTest exten
672       */
673      public void testShutdownNow_delayedTasks() throws InterruptedException {
674          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
675 <        List<ScheduledFuture> tasks = new ArrayList<>();
675 >        List<ScheduledFuture<?>> tasks = new ArrayList<>();
676          for (int i = 0; i < 3; i++) {
677              Runnable r = new NoOpRunnable();
678              tasks.add(p.schedule(r, 9, SECONDS));
# Line 716 | Line 680 | public class ScheduledExecutorTest exten
680              tasks.add(p.scheduleWithFixedDelay(r, 9, 9, SECONDS));
681          }
682          if (testImplementationDetails)
683 <            assertEquals(new HashSet(tasks), new HashSet(p.getQueue()));
683 >            assertEquals(new HashSet<Object>(tasks), new HashSet<Object>(p.getQueue()));
684          final List<Runnable> queuedTasks;
685          try {
686              queuedTasks = p.shutdownNow();
# Line 726 | Line 690 | public class ScheduledExecutorTest exten
690          assertTrue(p.isShutdown());
691          assertTrue(p.getQueue().isEmpty());
692          if (testImplementationDetails)
693 <            assertEquals(new HashSet(tasks), new HashSet(queuedTasks));
693 >            assertEquals(new HashSet<Object>(tasks), new HashSet<Object>(queuedTasks));
694          assertEquals(tasks.size(), queuedTasks.size());
695 <        for (ScheduledFuture task : tasks) {
695 >        for (ScheduledFuture<?> task : tasks) {
696              assertFalse(task.isDone());
697              assertFalse(task.isCancelled());
698          }
# Line 743 | Line 707 | public class ScheduledExecutorTest exten
707       * - setExecuteExistingDelayedTasksAfterShutdownPolicy
708       * - setContinueExistingPeriodicTasksAfterShutdownPolicy
709       */
710 +    @SuppressWarnings("FutureReturnValueIgnored")
711      public void testShutdown_cancellation() throws Exception {
712 <        Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE };
748 <        for (Boolean policy : allBooleans)
749 <    {
750 <        final int poolSize = 2;
712 >        final int poolSize = 4;
713          final ScheduledThreadPoolExecutor p
714              = new ScheduledThreadPoolExecutor(poolSize);
715 <        final boolean effectiveDelayedPolicy = (policy != Boolean.FALSE);
716 <        final boolean effectivePeriodicPolicy = (policy == Boolean.TRUE);
717 <        final boolean effectiveRemovePolicy = (policy == Boolean.TRUE);
718 <        if (policy != null) {
719 <            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(policy);
720 <            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(policy);
721 <            p.setRemoveOnCancelPolicy(policy);
722 <        }
715 >        final BlockingQueue<Runnable> q = p.getQueue();
716 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
717 >        final long delay = rnd.nextInt(2);
718 >        final int rounds = rnd.nextInt(1, 3);
719 >        final boolean effectiveDelayedPolicy;
720 >        final boolean effectivePeriodicPolicy;
721 >        final boolean effectiveRemovePolicy;
722 >
723 >        if (rnd.nextBoolean())
724 >            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(
725 >                effectiveDelayedPolicy = rnd.nextBoolean());
726 >        else
727 >            effectiveDelayedPolicy = true;
728          assertEquals(effectiveDelayedPolicy,
729                       p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
730 +
731 +        if (rnd.nextBoolean())
732 +            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(
733 +                effectivePeriodicPolicy = rnd.nextBoolean());
734 +        else
735 +            effectivePeriodicPolicy = false;
736          assertEquals(effectivePeriodicPolicy,
737                       p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
738 +
739 +        if (rnd.nextBoolean())
740 +            p.setRemoveOnCancelPolicy(
741 +                effectiveRemovePolicy = rnd.nextBoolean());
742 +        else
743 +            effectiveRemovePolicy = false;
744          assertEquals(effectiveRemovePolicy,
745                       p.getRemoveOnCancelPolicy());
746 <        // Strategy: Wedge the pool with poolSize "blocker" threads
746 >
747 >        final boolean periodicTasksContinue = effectivePeriodicPolicy && rnd.nextBoolean();
748 >
749 >        // Strategy: Wedge the pool with one wave of "blocker" tasks,
750 >        // then add a second wave that waits in the queue until unblocked.
751          final AtomicInteger ran = new AtomicInteger(0);
752          final CountDownLatch poolBlocked = new CountDownLatch(poolSize);
753          final CountDownLatch unblock = new CountDownLatch(1);
754 <        final CountDownLatch periodicLatch1 = new CountDownLatch(2);
755 <        final CountDownLatch periodicLatch2 = new CountDownLatch(2);
756 <        Runnable task = new CheckedRunnable() { public void realRun()
757 <                                                    throws InterruptedException {
758 <            poolBlocked.countDown();
759 <            await(unblock);
760 <            ran.getAndIncrement();
761 <        }};
762 <        List<Future<?>> blockers = new ArrayList<>();
763 <        List<Future<?>> periodics = new ArrayList<>();
764 <        List<Future<?>> delayeds = new ArrayList<>();
765 <        for (int i = 0; i < poolSize; i++)
766 <            blockers.add(p.submit(task));
754 >        final RuntimeException exception = new RuntimeException();
755 >
756 >        class Task implements Runnable {
757 >            public void run() {
758 >                try {
759 >                    ran.getAndIncrement();
760 >                    poolBlocked.countDown();
761 >                    await(unblock);
762 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
763 >            }
764 >        }
765 >
766 >        class PeriodicTask extends Task {
767 >            PeriodicTask(int rounds) { this.rounds = rounds; }
768 >            int rounds;
769 >            public void run() {
770 >                if (--rounds == 0) super.run();
771 >                // throw exception to surely terminate this periodic task,
772 >                // but in a separate execution and in a detectable way.
773 >                if (rounds == -1) throw exception;
774 >            }
775 >        }
776 >
777 >        Runnable task = new Task();
778 >
779 >        List<Future<?>> immediates = new ArrayList<>();
780 >        List<Future<?>> delayeds   = new ArrayList<>();
781 >        List<Future<?>> periodics  = new ArrayList<>();
782 >
783 >        immediates.add(p.submit(task));
784 >        delayeds.add(p.schedule(task, delay, MILLISECONDS));
785 >        periodics.add(p.scheduleAtFixedRate(
786 >                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
787 >        periodics.add(p.scheduleWithFixedDelay(
788 >                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
789 >
790          await(poolBlocked);
791  
792 <        periodics.add(p.scheduleAtFixedRate(countDowner(periodicLatch1),
793 <                                            1, 1, MILLISECONDS));
794 <        periodics.add(p.scheduleWithFixedDelay(countDowner(periodicLatch2),
795 <                                               1, 1, MILLISECONDS));
796 <        delayeds.add(p.schedule(task, 1, MILLISECONDS));
792 >        assertEquals(poolSize, ran.get());
793 >        assertEquals(poolSize, p.getActiveCount());
794 >        assertTrue(q.isEmpty());
795 >
796 >        // Add second wave of tasks.
797 >        immediates.add(p.submit(task));
798 >        delayeds.add(p.schedule(task, effectiveDelayedPolicy ? delay : LONG_DELAY_MS, MILLISECONDS));
799 >        periodics.add(p.scheduleAtFixedRate(
800 >                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
801 >        periodics.add(p.scheduleWithFixedDelay(
802 >                          new PeriodicTask(rounds), delay, 1, MILLISECONDS));
803 >
804 >        assertEquals(poolSize, q.size());
805 >        assertEquals(poolSize, ran.get());
806 >
807 >        immediates.forEach(
808 >            f -> assertTrue(((ScheduledFuture)f).getDelay(NANOSECONDS) <= 0L));
809 >
810 >        Stream.of(immediates, delayeds, periodics).flatMap(Collection::stream)
811 >            .forEach(f -> assertFalse(f.isDone()));
812  
792        assertTrue(p.getQueue().containsAll(periodics));
793        assertTrue(p.getQueue().containsAll(delayeds));
813          try { p.shutdown(); } catch (SecurityException ok) { return; }
814          assertTrue(p.isShutdown());
815 +        assertTrue(p.isTerminating());
816          assertFalse(p.isTerminated());
817 <        for (Future<?> periodic : periodics) {
818 <            assertTrue(effectivePeriodicPolicy ^ periodic.isCancelled());
819 <            assertTrue(effectivePeriodicPolicy ^ periodic.isDone());
820 <        }
821 <        for (Future<?> delayed : delayeds) {
822 <            assertTrue(effectiveDelayedPolicy ^ delayed.isCancelled());
823 <            assertTrue(effectiveDelayedPolicy ^ delayed.isDone());
824 <        }
825 <        if (testImplementationDetails) {
826 <            assertEquals(effectivePeriodicPolicy,
827 <                         p.getQueue().containsAll(periodics));
828 <            assertEquals(effectiveDelayedPolicy,
829 <                         p.getQueue().containsAll(delayeds));
830 <        }
831 <        // Release all pool threads
832 <        unblock.countDown();
833 <
834 <        for (Future<?> delayed : delayeds) {
835 <            if (effectiveDelayedPolicy) {
836 <                assertNull(delayed.get());
837 <            }
838 <        }
839 <        if (effectivePeriodicPolicy) {
840 <            await(periodicLatch1);
841 <            await(periodicLatch2);
842 <            for (Future<?> periodic : periodics) {
843 <                assertTrue(periodic.cancel(false));
844 <                assertTrue(periodic.isCancelled());
845 <                assertTrue(periodic.isDone());
846 <            }
817 >
818 >        if (rnd.nextBoolean())
819 >            assertThrows(
820 >                RejectedExecutionException.class,
821 >                () -> p.submit(task),
822 >                () -> p.schedule(task, 1, SECONDS),
823 >                () -> p.scheduleAtFixedRate(
824 >                    new PeriodicTask(1), 1, 1, SECONDS),
825 >                () -> p.scheduleWithFixedDelay(
826 >                    new PeriodicTask(2), 1, 1, SECONDS));
827 >
828 >        assertTrue(q.contains(immediates.get(1)));
829 >        assertTrue(!effectiveDelayedPolicy
830 >                   ^ q.contains(delayeds.get(1)));
831 >        assertTrue(!effectivePeriodicPolicy
832 >                   ^ q.containsAll(periodics.subList(2, 4)));
833 >
834 >        immediates.forEach(f -> assertFalse(f.isDone()));
835 >
836 >        assertFalse(delayeds.get(0).isDone());
837 >        if (effectiveDelayedPolicy)
838 >            assertFalse(delayeds.get(1).isDone());
839 >        else
840 >            assertTrue(delayeds.get(1).isCancelled());
841 >
842 >        if (effectivePeriodicPolicy)
843 >            periodics.forEach(
844 >                f -> {
845 >                    assertFalse(f.isDone());
846 >                    if (!periodicTasksContinue) {
847 >                        assertTrue(f.cancel(false));
848 >                        assertTrue(f.isCancelled());
849 >                    }
850 >                });
851 >        else {
852 >            periodics.subList(0, 2).forEach(f -> assertFalse(f.isDone()));
853 >            periodics.subList(2, 4).forEach(f -> assertTrue(f.isCancelled()));
854          }
855 <        for (Future<?> blocker : blockers) assertNull(blocker.get());
855 >
856 >        unblock.countDown();    // Release all pool threads
857 >
858          assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
859 +        assertFalse(p.isTerminating());
860          assertTrue(p.isTerminated());
861 <        assertEquals(2 + (effectiveDelayedPolicy ? 1 : 0), ran.get());
862 <    }}
861 >
862 >        assertTrue(q.isEmpty());
863 >
864 >        Stream.of(immediates, delayeds, periodics).flatMap(Collection::stream)
865 >            .forEach(f -> assertTrue(f.isDone()));
866 >
867 >        for (Future<?> f : immediates) assertNull(f.get());
868 >
869 >        assertNull(delayeds.get(0).get());
870 >        if (effectiveDelayedPolicy)
871 >            assertNull(delayeds.get(1).get());
872 >        else
873 >            assertTrue(delayeds.get(1).isCancelled());
874 >
875 >        if (periodicTasksContinue)
876 >            periodics.forEach(
877 >                f -> {
878 >                    try { f.get(); }
879 >                    catch (ExecutionException success) {
880 >                        assertSame(exception, success.getCause());
881 >                    }
882 >                    catch (Throwable fail) { threadUnexpectedException(fail); }
883 >                });
884 >        else
885 >            periodics.forEach(f -> assertTrue(f.isCancelled()));
886 >
887 >        assertEquals(poolSize + 1
888 >                     + (effectiveDelayedPolicy ? 1 : 0)
889 >                     + (periodicTasksContinue ? 2 : 0),
890 >                     ran.get());
891 >    }
892  
893      /**
894       * completed submit of callable returns result
# Line 868 | Line 927 | public class ScheduledExecutorTest exten
927      }
928  
929      /**
930 <     * invokeAny(null) throws NPE
930 >     * invokeAny(null) throws NullPointerException
931       */
932      public void testInvokeAny1() throws Exception {
933          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
# Line 881 | Line 940 | public class ScheduledExecutorTest exten
940      }
941  
942      /**
943 <     * invokeAny(empty collection) throws IAE
943 >     * invokeAny(empty collection) throws IllegalArgumentException
944       */
945      public void testInvokeAny2() throws Exception {
946          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
# Line 894 | Line 953 | public class ScheduledExecutorTest exten
953      }
954  
955      /**
956 <     * invokeAny(c) throws NPE if c has null elements
956 >     * invokeAny(c) throws NullPointerException if c has null elements
957       */
958      public void testInvokeAny3() throws Exception {
959          CountDownLatch latch = new CountDownLatch(1);
# Line 956 | Line 1015 | public class ScheduledExecutorTest exten
1015      }
1016  
1017      /**
1018 <     * invokeAll(empty collection) returns empty collection
1018 >     * invokeAll(empty collection) returns empty list
1019       */
1020      public void testInvokeAll2() throws Exception {
1021          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1022 +        final Collection<Callable<String>> emptyCollection
1023 +            = Collections.emptyList();
1024          try (PoolCleaner cleaner = cleaner(e)) {
1025 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
1025 >            List<Future<String>> r = e.invokeAll(emptyCollection);
1026              assertTrue(r.isEmpty());
1027          }
1028      }
# Line 1024 | Line 1085 | public class ScheduledExecutorTest exten
1085          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1086          try (PoolCleaner cleaner = cleaner(e)) {
1087              try {
1088 <                e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1088 >                e.invokeAny(null, randomTimeout(), randomTimeUnit());
1089                  shouldThrow();
1090              } catch (NullPointerException success) {}
1091          }
1092      }
1093  
1094      /**
1095 <     * timed invokeAny(,,null) throws NPE
1095 >     * timed invokeAny(,,null) throws NullPointerException
1096       */
1097      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1098          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
# Line 1039 | Line 1100 | public class ScheduledExecutorTest exten
1100              List<Callable<String>> l = new ArrayList<>();
1101              l.add(new StringTask());
1102              try {
1103 <                e.invokeAny(l, MEDIUM_DELAY_MS, null);
1103 >                e.invokeAny(l, randomTimeout(), null);
1104                  shouldThrow();
1105              } catch (NullPointerException success) {}
1106          }
1107      }
1108  
1109      /**
1110 <     * timed invokeAny(empty collection) throws IAE
1110 >     * timed invokeAny(empty collection) throws IllegalArgumentException
1111       */
1112      public void testTimedInvokeAny2() throws Exception {
1113          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1114 +        final Collection<Callable<String>> emptyCollection
1115 +            = Collections.emptyList();
1116          try (PoolCleaner cleaner = cleaner(e)) {
1117              try {
1118 <                e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1118 >                e.invokeAny(emptyCollection, randomTimeout(), randomTimeUnit());
1119                  shouldThrow();
1120              } catch (IllegalArgumentException success) {}
1121          }
# Line 1069 | Line 1132 | public class ScheduledExecutorTest exten
1132              l.add(latchAwaitingStringTask(latch));
1133              l.add(null);
1134              try {
1135 <                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1135 >                e.invokeAny(l, randomTimeout(), randomTimeUnit());
1136                  shouldThrow();
1137              } catch (NullPointerException success) {}
1138              latch.countDown();
# Line 1118 | Line 1181 | public class ScheduledExecutorTest exten
1181          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1182          try (PoolCleaner cleaner = cleaner(e)) {
1183              try {
1184 <                e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1184 >                e.invokeAll(null, randomTimeout(), randomTimeUnit());
1185                  shouldThrow();
1186              } catch (NullPointerException success) {}
1187          }
# Line 1133 | Line 1196 | public class ScheduledExecutorTest exten
1196              List<Callable<String>> l = new ArrayList<>();
1197              l.add(new StringTask());
1198              try {
1199 <                e.invokeAll(l, MEDIUM_DELAY_MS, null);
1199 >                e.invokeAll(l, randomTimeout(), null);
1200                  shouldThrow();
1201              } catch (NullPointerException success) {}
1202          }
1203      }
1204  
1205      /**
1206 <     * timed invokeAll(empty collection) returns empty collection
1206 >     * timed invokeAll(empty collection) returns empty list
1207       */
1208      public void testTimedInvokeAll2() throws Exception {
1209          final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1210 +        final Collection<Callable<String>> emptyCollection
1211 +            = Collections.emptyList();
1212          try (PoolCleaner cleaner = cleaner(e)) {
1213 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(),
1214 <                                                 MEDIUM_DELAY_MS, MILLISECONDS);
1213 >            List<Future<String>> r =
1214 >                e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit());
1215              assertTrue(r.isEmpty());
1216          }
1217      }
# Line 1161 | Line 1226 | public class ScheduledExecutorTest exten
1226              l.add(new StringTask());
1227              l.add(null);
1228              try {
1229 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1229 >                e.invokeAll(l, randomTimeout(), randomTimeUnit());
1230                  shouldThrow();
1231              } catch (NullPointerException success) {}
1232          }
# Line 1226 | Line 1291 | public class ScheduledExecutorTest exten
1291                      p.invokeAll(tasks, timeout, MILLISECONDS);
1292                  assertEquals(tasks.size(), futures.size());
1293                  assertTrue(millisElapsedSince(startTime) >= timeout);
1294 <                for (Future future : futures)
1294 >                for (Future<?> future : futures)
1295                      assertTrue(future.isDone());
1296                  assertTrue(futures.get(1).isCancelled());
1297                  try {
# Line 1247 | Line 1312 | public class ScheduledExecutorTest exten
1312       * one-shot task from executing.
1313       * https://bugs.openjdk.java.net/browse/JDK-8051859
1314       */
1315 +    @SuppressWarnings("FutureReturnValueIgnored")
1316      public void testScheduleWithFixedDelay_overflow() throws Exception {
1317          final CountDownLatch delayedDone = new CountDownLatch(1);
1318          final CountDownLatch immediateDone = new CountDownLatch(1);
1319          final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
1320          try (PoolCleaner cleaner = cleaner(p)) {
1321 <            final Runnable immediate = new Runnable() { public void run() {
1256 <                immediateDone.countDown();
1257 <            }};
1258 <            final Runnable delayed = new Runnable() { public void run() {
1321 >            final Runnable delayed = () -> {
1322                  delayedDone.countDown();
1323 <                p.submit(immediate);
1324 <            }};
1323 >                p.submit(() -> immediateDone.countDown());
1324 >            };
1325              p.scheduleWithFixedDelay(delayed, 0L, Long.MAX_VALUE, SECONDS);
1326              await(delayedDone);
1327              await(immediateDone);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines