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.39 by dl, Fri May 6 11:22:07 2011 UTC vs.
Revision 1.91 by jsr166, Wed Mar 29 16:53:20 2017 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 import junit.framework.*;
10 import java.util.*;
11 import java.util.concurrent.*;
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 < import java.util.concurrent.atomic.*;
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.HashSet;
15 > import java.util.List;
16 > import java.util.concurrent.BlockingQueue;
17 > import java.util.concurrent.Callable;
18 > import java.util.concurrent.CancellationException;
19 > import java.util.concurrent.CountDownLatch;
20 > import java.util.concurrent.ExecutionException;
21 > import java.util.concurrent.ExecutorService;
22 > import java.util.concurrent.Future;
23 > import java.util.concurrent.RejectedExecutionException;
24 > import java.util.concurrent.ScheduledFuture;
25 > import java.util.concurrent.ScheduledThreadPoolExecutor;
26 > import java.util.concurrent.ThreadFactory;
27 > import java.util.concurrent.ThreadLocalRandom;
28 > import java.util.concurrent.ThreadPoolExecutor;
29 > import java.util.concurrent.atomic.AtomicBoolean;
30 > import java.util.concurrent.atomic.AtomicInteger;
31 > import java.util.concurrent.atomic.AtomicLong;
32 > import java.util.stream.Stream;
33 >
34 > import junit.framework.Test;
35 > import junit.framework.TestSuite;
36  
37   public class ScheduledExecutorTest extends JSR166TestCase {
38      public static void main(String[] args) {
39 <        junit.textui.TestRunner.run(suite());
39 >        main(suite(), args);
40      }
41      public static Test suite() {
42          return new TestSuite(ScheduledExecutorTest.class);
43      }
44  
23
45      /**
46       * execute successfully executes a runnable
47       */
48      public void testExecute() throws InterruptedException {
49 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
50 <        final CountDownLatch done = new CountDownLatch(1);
51 <        final Runnable task = new CheckedRunnable() {
52 <            public void realRun() {
53 <                done.countDown();
33 <            }};
34 <        try {
49 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
50 >        try (PoolCleaner cleaner = cleaner(p)) {
51 >            final CountDownLatch done = new CountDownLatch(1);
52 >            final Runnable task = new CheckedRunnable() {
53 >                public void realRun() { done.countDown(); }};
54              p.execute(task);
55 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
37 <        } finally {
38 <            joinPool(p);
55 >            await(done);
56          }
57      }
58  
42
59      /**
60       * delayed schedule of callable successfully executes after delay
61       */
62      public void testSchedule1() throws Exception {
63 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
64 <        final long t0 = System.nanoTime();
65 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
66 <        final CountDownLatch done = new CountDownLatch(1);
51 <        try {
63 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
64 >        try (PoolCleaner cleaner = cleaner(p)) {
65 >            final long startTime = System.nanoTime();
66 >            final CountDownLatch done = new CountDownLatch(1);
67              Callable task = new CheckedCallable<Boolean>() {
68                  public Boolean realCall() {
69                      done.countDown();
70 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
70 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
71                      return Boolean.TRUE;
72                  }};
73 <            Future f = p.schedule(task, SHORT_DELAY_MS, MILLISECONDS);
74 <            assertEquals(Boolean.TRUE, f.get());
75 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
73 >            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
74 >            assertSame(Boolean.TRUE, f.get());
75 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
76              assertTrue(done.await(0L, MILLISECONDS));
62        } finally {
63            joinPool(p);
77          }
78      }
79  
# Line 68 | Line 81 | public class ScheduledExecutorTest exten
81       * delayed schedule of runnable successfully executes after delay
82       */
83      public void testSchedule3() throws Exception {
84 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
85 <        final long t0 = System.nanoTime();
86 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
87 <        final CountDownLatch done = new CountDownLatch(1);
75 <        try {
84 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
85 >        try (PoolCleaner cleaner = cleaner(p)) {
86 >            final long startTime = System.nanoTime();
87 >            final CountDownLatch done = new CountDownLatch(1);
88              Runnable task = new CheckedRunnable() {
89                  public void realRun() {
90                      done.countDown();
91 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
91 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
92                  }};
93 <            Future f = p.schedule(task, SHORT_DELAY_MS, MILLISECONDS);
94 <            assertNull(f.get());
95 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
96 <            assertTrue(done.await(0L, MILLISECONDS));
85 <        } finally {
86 <            joinPool(p);
93 >            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
94 >            await(done);
95 >            assertNull(f.get(LONG_DELAY_MS, MILLISECONDS));
96 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
97          }
98      }
99  
# Line 91 | Line 101 | public class ScheduledExecutorTest exten
101       * scheduleAtFixedRate executes runnable after given initial delay
102       */
103      public void testSchedule4() throws Exception {
104 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
105 <        final long t0 = System.nanoTime();
106 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
107 <        final CountDownLatch done = new CountDownLatch(1);
98 <        try {
104 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
105 >        try (PoolCleaner cleaner = cleaner(p)) {
106 >            final long startTime = System.nanoTime();
107 >            final CountDownLatch done = new CountDownLatch(1);
108              Runnable task = new CheckedRunnable() {
109                  public void realRun() {
110                      done.countDown();
111 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
111 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
112                  }};
113              ScheduledFuture f =
114 <                p.scheduleAtFixedRate(task, SHORT_DELAY_MS,
115 <                                      SHORT_DELAY_MS, MILLISECONDS);
116 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
117 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
114 >                p.scheduleAtFixedRate(task, timeoutMillis(),
115 >                                      LONG_DELAY_MS, MILLISECONDS);
116 >            await(done);
117 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
118              f.cancel(true);
110        } finally {
111            joinPool(p);
119          }
120      }
121  
122      /**
123       * scheduleWithFixedDelay executes runnable after given initial delay
124       */
125 <    public void testSchedule5() throws InterruptedException {
126 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
127 <        final long t0 = System.nanoTime();
128 <        final long timeoutNanos = SHORT_DELAY_MS * 1000L * 1000L;
129 <        final CountDownLatch done = new CountDownLatch(1);
123 <        try {
125 >    public void testSchedule5() throws Exception {
126 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
127 >        try (PoolCleaner cleaner = cleaner(p)) {
128 >            final long startTime = System.nanoTime();
129 >            final CountDownLatch done = new CountDownLatch(1);
130              Runnable task = new CheckedRunnable() {
131                  public void realRun() {
132                      done.countDown();
133 <                    assertTrue(System.nanoTime() - t0 >= timeoutNanos);
133 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
134                  }};
135              ScheduledFuture f =
136 <                p.scheduleWithFixedDelay(task, SHORT_DELAY_MS,
137 <                                         SHORT_DELAY_MS, MILLISECONDS);
138 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
139 <            assertTrue(System.nanoTime() - t0 >= timeoutNanos);
136 >                p.scheduleWithFixedDelay(task, timeoutMillis(),
137 >                                         LONG_DELAY_MS, MILLISECONDS);
138 >            await(done);
139 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
140              f.cancel(true);
135        } finally {
136            joinPool(p);
141          }
142      }
143  
# Line 143 | Line 147 | public class ScheduledExecutorTest exten
147      }
148  
149      /**
150 <     * scheduleAtFixedRate executes series of tasks at given rate
150 >     * scheduleAtFixedRate executes series of tasks at given rate.
151 >     * Eventually, it must hold that:
152 >     *   cycles - 1 <= elapsedMillis/delay < cycles
153       */
154      public void testFixedRateSequence() throws InterruptedException {
155 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
156 <        RunnableCounter counter = new RunnableCounter();
157 <        ScheduledFuture h =
158 <            p.scheduleAtFixedRate(counter, 0, 1, MILLISECONDS);
159 <        delay(SMALL_DELAY_MS);
160 <        h.cancel(true);
161 <        int c = counter.count.get();
162 <        // By time scaling conventions, we must have at least
163 <        // an execution per SHORT delay, but no more than one SHORT more
164 <        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
165 <        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
166 <        joinPool(p);
155 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
156 >        try (PoolCleaner cleaner = cleaner(p)) {
157 >            for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
158 >                final long startTime = System.nanoTime();
159 >                final int cycles = 8;
160 >                final CountDownLatch done = new CountDownLatch(cycles);
161 >                final Runnable task = new CheckedRunnable() {
162 >                    public void realRun() { done.countDown(); }};
163 >                final ScheduledFuture periodicTask =
164 >                    p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
165 >                final int totalDelayMillis = (cycles - 1) * delay;
166 >                await(done, totalDelayMillis + LONG_DELAY_MS);
167 >                periodicTask.cancel(true);
168 >                final long elapsedMillis = millisElapsedSince(startTime);
169 >                assertTrue(elapsedMillis >= totalDelayMillis);
170 >                if (elapsedMillis <= cycles * delay)
171 >                    return;
172 >                // else retry with longer delay
173 >            }
174 >            fail("unexpected execution rate");
175 >        }
176      }
177  
178      /**
179 <     * scheduleWithFixedDelay executes series of tasks with given period
179 >     * scheduleWithFixedDelay executes series of tasks with given period.
180 >     * Eventually, it must hold that each task starts at least delay and at
181 >     * most 2 * delay after the termination of the previous task.
182       */
183      public void testFixedDelaySequence() throws InterruptedException {
184 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
185 <        RunnableCounter counter = new RunnableCounter();
186 <        ScheduledFuture h =
187 <            p.scheduleWithFixedDelay(counter, 0, 1, MILLISECONDS);
188 <        delay(SMALL_DELAY_MS);
189 <        h.cancel(true);
190 <        int c = counter.count.get();
191 <        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
192 <        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
193 <        joinPool(p);
184 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
185 >        try (PoolCleaner cleaner = cleaner(p)) {
186 >            for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
187 >                final long startTime = System.nanoTime();
188 >                final AtomicLong previous = new AtomicLong(startTime);
189 >                final AtomicBoolean tryLongerDelay = new AtomicBoolean(false);
190 >                final int cycles = 8;
191 >                final CountDownLatch done = new CountDownLatch(cycles);
192 >                final int d = delay;
193 >                final Runnable task = new CheckedRunnable() {
194 >                    public void realRun() {
195 >                        long now = System.nanoTime();
196 >                        long elapsedMillis
197 >                            = NANOSECONDS.toMillis(now - previous.get());
198 >                        if (done.getCount() == cycles) { // first execution
199 >                            if (elapsedMillis >= d)
200 >                                tryLongerDelay.set(true);
201 >                        } else {
202 >                            assertTrue(elapsedMillis >= d);
203 >                            if (elapsedMillis >= 2 * d)
204 >                                tryLongerDelay.set(true);
205 >                        }
206 >                        previous.set(now);
207 >                        done.countDown();
208 >                    }};
209 >                final ScheduledFuture periodicTask =
210 >                    p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
211 >                final int totalDelayMillis = (cycles - 1) * delay;
212 >                await(done, totalDelayMillis + cycles * LONG_DELAY_MS);
213 >                periodicTask.cancel(true);
214 >                final long elapsedMillis = millisElapsedSince(startTime);
215 >                assertTrue(elapsedMillis >= totalDelayMillis);
216 >                if (!tryLongerDelay.get())
217 >                    return;
218 >                // else retry with longer delay
219 >            }
220 >            fail("unexpected execution rate");
221 >        }
222      }
223  
179
224      /**
225       * execute(null) throws NPE
226       */
227      public void testExecuteNull() throws InterruptedException {
228 <        ScheduledThreadPoolExecutor se = null;
229 <        try {
230 <            se = new ScheduledThreadPoolExecutor(1);
231 <            se.execute(null);
232 <            shouldThrow();
233 <        } catch (NullPointerException success) {}
234 <
191 <        joinPool(se);
228 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
229 >        try (PoolCleaner cleaner = cleaner(p)) {
230 >            try {
231 >                p.execute(null);
232 >                shouldThrow();
233 >            } catch (NullPointerException success) {}
234 >        }
235      }
236  
237      /**
238       * schedule(null) throws NPE
239       */
240      public void testScheduleNull() throws InterruptedException {
241 <        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
242 <        try {
243 <            TrackedCallable callable = null;
244 <            Future f = se.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
245 <            shouldThrow();
246 <        } catch (NullPointerException success) {}
247 <        joinPool(se);
241 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
242 >        try (PoolCleaner cleaner = cleaner(p)) {
243 >            try {
244 >                TrackedCallable callable = null;
245 >                Future f = p.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
246 >                shouldThrow();
247 >            } catch (NullPointerException success) {}
248 >        }
249      }
250  
251      /**
252       * execute throws RejectedExecutionException if shutdown
253       */
254      public void testSchedule1_RejectedExecutionException() throws InterruptedException {
255 <        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
256 <        try {
257 <            se.shutdown();
258 <            se.schedule(new NoOpRunnable(),
259 <                        MEDIUM_DELAY_MS, MILLISECONDS);
260 <            shouldThrow();
261 <        } catch (RejectedExecutionException success) {
262 <        } catch (SecurityException ok) {
255 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
256 >        try (PoolCleaner cleaner = cleaner(p)) {
257 >            try {
258 >                p.shutdown();
259 >                p.schedule(new NoOpRunnable(),
260 >                           MEDIUM_DELAY_MS, MILLISECONDS);
261 >                shouldThrow();
262 >            } catch (RejectedExecutionException success) {
263 >            } catch (SecurityException ok) {}
264          }
220
221        joinPool(se);
265      }
266  
267      /**
268       * schedule throws RejectedExecutionException if shutdown
269       */
270      public void testSchedule2_RejectedExecutionException() throws InterruptedException {
271 <        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
272 <        try {
273 <            se.shutdown();
274 <            se.schedule(new NoOpCallable(),
275 <                        MEDIUM_DELAY_MS, MILLISECONDS);
276 <            shouldThrow();
277 <        } catch (RejectedExecutionException success) {
278 <        } catch (SecurityException ok) {
271 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
272 >        try (PoolCleaner cleaner = cleaner(p)) {
273 >            try {
274 >                p.shutdown();
275 >                p.schedule(new NoOpCallable(),
276 >                           MEDIUM_DELAY_MS, MILLISECONDS);
277 >                shouldThrow();
278 >            } catch (RejectedExecutionException success) {
279 >            } catch (SecurityException ok) {}
280          }
237        joinPool(se);
281      }
282  
283      /**
284       * schedule callable throws RejectedExecutionException if shutdown
285       */
286      public void testSchedule3_RejectedExecutionException() throws InterruptedException {
287 <        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
288 <        try {
289 <            se.shutdown();
290 <            se.schedule(new NoOpCallable(),
291 <                        MEDIUM_DELAY_MS, MILLISECONDS);
292 <            shouldThrow();
293 <        } catch (RejectedExecutionException success) {
294 <        } catch (SecurityException ok) {
287 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
288 >        try (PoolCleaner cleaner = cleaner(p)) {
289 >            try {
290 >                p.shutdown();
291 >                p.schedule(new NoOpCallable(),
292 >                           MEDIUM_DELAY_MS, MILLISECONDS);
293 >                shouldThrow();
294 >            } catch (RejectedExecutionException success) {
295 >            } catch (SecurityException ok) {}
296          }
253        joinPool(se);
297      }
298  
299      /**
300       * scheduleAtFixedRate throws RejectedExecutionException if shutdown
301       */
302      public void testScheduleAtFixedRate1_RejectedExecutionException() throws InterruptedException {
303 <        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
304 <        try {
305 <            se.shutdown();
306 <            se.scheduleAtFixedRate(new NoOpRunnable(),
307 <                                   MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
308 <            shouldThrow();
309 <        } catch (RejectedExecutionException success) {
310 <        } catch (SecurityException ok) {
303 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
304 >        try (PoolCleaner cleaner = cleaner(p)) {
305 >            try {
306 >                p.shutdown();
307 >                p.scheduleAtFixedRate(new NoOpRunnable(),
308 >                                      MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
309 >                shouldThrow();
310 >            } catch (RejectedExecutionException success) {
311 >            } catch (SecurityException ok) {}
312          }
269        joinPool(se);
313      }
314  
315      /**
316       * scheduleWithFixedDelay throws RejectedExecutionException if shutdown
317       */
318      public void testScheduleWithFixedDelay1_RejectedExecutionException() throws InterruptedException {
319 <        ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
320 <        try {
321 <            se.shutdown();
322 <            se.scheduleWithFixedDelay(new NoOpRunnable(),
323 <                                      MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
324 <            shouldThrow();
325 <        } catch (RejectedExecutionException success) {
326 <        } catch (SecurityException ok) {
319 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
320 >        try (PoolCleaner cleaner = cleaner(p)) {
321 >            try {
322 >                p.shutdown();
323 >                p.scheduleWithFixedDelay(new NoOpRunnable(),
324 >                                         MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
325 >                shouldThrow();
326 >            } catch (RejectedExecutionException success) {
327 >            } catch (SecurityException ok) {}
328          }
285        joinPool(se);
329      }
330  
331      /**
# Line 290 | Line 333 | public class ScheduledExecutorTest exten
333       * thread becomes active
334       */
335      public void testGetActiveCount() throws InterruptedException {
293        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
294        final CountDownLatch threadStarted = new CountDownLatch(1);
336          final CountDownLatch done = new CountDownLatch(1);
337 <        try {
337 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
338 >        try (PoolCleaner cleaner = cleaner(p, done)) {
339 >            final CountDownLatch threadStarted = new CountDownLatch(1);
340              assertEquals(0, p.getActiveCount());
341              p.execute(new CheckedRunnable() {
342                  public void realRun() throws InterruptedException {
343                      threadStarted.countDown();
344                      assertEquals(1, p.getActiveCount());
345 <                    done.await();
345 >                    await(done);
346                  }});
347 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
347 >            await(threadStarted);
348              assertEquals(1, p.getActiveCount());
306        } finally {
307            done.countDown();
308            joinPool(p);
349          }
350      }
351  
# Line 315 | Line 355 | public class ScheduledExecutorTest exten
355       */
356      public void testGetCompletedTaskCount() throws InterruptedException {
357          final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
358 <        final CountDownLatch threadStarted = new CountDownLatch(1);
359 <        final CountDownLatch threadProceed = new CountDownLatch(1);
360 <        final CountDownLatch threadDone = new CountDownLatch(1);
361 <        try {
358 >        try (PoolCleaner cleaner = cleaner(p)) {
359 >            final CountDownLatch threadStarted = new CountDownLatch(1);
360 >            final CountDownLatch threadProceed = new CountDownLatch(1);
361 >            final CountDownLatch threadDone = new CountDownLatch(1);
362              assertEquals(0, p.getCompletedTaskCount());
363              p.execute(new CheckedRunnable() {
364                  public void realRun() throws InterruptedException {
365                      threadStarted.countDown();
366                      assertEquals(0, p.getCompletedTaskCount());
367 <                    threadProceed.await();
367 >                    await(threadProceed);
368                      threadDone.countDown();
369                  }});
370 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
370 >            await(threadStarted);
371              assertEquals(0, p.getCompletedTaskCount());
372              threadProceed.countDown();
373 <            threadDone.await();
374 <            delay(SHORT_DELAY_MS);
375 <            assertEquals(1, p.getCompletedTaskCount());
376 <        } finally {
377 <            joinPool(p);
373 >            await(threadDone);
374 >            long startTime = System.nanoTime();
375 >            while (p.getCompletedTaskCount() != 1) {
376 >                if (millisElapsedSince(startTime) > LONG_DELAY_MS)
377 >                    fail("timed out");
378 >                Thread.yield();
379 >            }
380          }
381      }
382  
# Line 343 | Line 385 | public class ScheduledExecutorTest exten
385       */
386      public void testGetCorePoolSize() throws InterruptedException {
387          ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
388 <        assertEquals(1, p.getCorePoolSize());
389 <        joinPool(p);
388 >        try (PoolCleaner cleaner = cleaner(p)) {
389 >            assertEquals(1, p.getCorePoolSize());
390 >        }
391      }
392  
393      /**
# Line 356 | Line 399 | public class ScheduledExecutorTest exten
399          final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(THREADS);
400          final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
401          final CountDownLatch done = new CountDownLatch(1);
402 <        try {
402 >        try (PoolCleaner cleaner = cleaner(p, done)) {
403              assertEquals(0, p.getLargestPoolSize());
404              for (int i = 0; i < THREADS; i++)
405                  p.execute(new CheckedRunnable() {
406                      public void realRun() throws InterruptedException {
407                          threadsStarted.countDown();
408 <                        done.await();
408 >                        await(done);
409                          assertEquals(THREADS, p.getLargestPoolSize());
410                      }});
411 <            assertTrue(threadsStarted.await(SMALL_DELAY_MS, MILLISECONDS));
369 <            assertEquals(THREADS, p.getLargestPoolSize());
370 <        } finally {
371 <            done.countDown();
372 <            joinPool(p);
411 >            await(threadsStarted);
412              assertEquals(THREADS, p.getLargestPoolSize());
413          }
414 +        assertEquals(THREADS, p.getLargestPoolSize());
415      }
416  
417      /**
# Line 382 | Line 422 | public class ScheduledExecutorTest exten
422          final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
423          final CountDownLatch threadStarted = new CountDownLatch(1);
424          final CountDownLatch done = new CountDownLatch(1);
425 <        try {
425 >        try (PoolCleaner cleaner = cleaner(p, done)) {
426              assertEquals(0, p.getPoolSize());
427              p.execute(new CheckedRunnable() {
428                  public void realRun() throws InterruptedException {
429                      threadStarted.countDown();
430                      assertEquals(1, p.getPoolSize());
431 <                    done.await();
431 >                    await(done);
432                  }});
433 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
433 >            await(threadStarted);
434              assertEquals(1, p.getPoolSize());
395        } finally {
396            done.countDown();
397            joinPool(p);
435          }
436      }
437  
# Line 403 | Line 440 | public class ScheduledExecutorTest exten
440       * submitted
441       */
442      public void testGetTaskCount() throws InterruptedException {
443 <        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
407 <        final CountDownLatch threadStarted = new CountDownLatch(1);
443 >        final int TASKS = 3;
444          final CountDownLatch done = new CountDownLatch(1);
445 <        final int TASKS = 5;
446 <        try {
445 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
446 >        try (PoolCleaner cleaner = cleaner(p, done)) {
447 >            final CountDownLatch threadStarted = new CountDownLatch(1);
448              assertEquals(0, p.getTaskCount());
449 <            for (int i = 0; i < TASKS; i++)
449 >            assertEquals(0, p.getCompletedTaskCount());
450 >            p.execute(new CheckedRunnable() {
451 >                public void realRun() throws InterruptedException {
452 >                    threadStarted.countDown();
453 >                    await(done);
454 >                }});
455 >            await(threadStarted);
456 >            assertEquals(1, p.getTaskCount());
457 >            assertEquals(0, p.getCompletedTaskCount());
458 >            for (int i = 0; i < TASKS; i++) {
459 >                assertEquals(1 + i, p.getTaskCount());
460                  p.execute(new CheckedRunnable() {
461                      public void realRun() throws InterruptedException {
462                          threadStarted.countDown();
463 <                        done.await();
463 >                        assertEquals(1 + TASKS, p.getTaskCount());
464 >                        await(done);
465                      }});
466 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
467 <            assertEquals(TASKS, p.getTaskCount());
468 <        } finally {
421 <            done.countDown();
422 <            joinPool(p);
466 >            }
467 >            assertEquals(1 + TASKS, p.getTaskCount());
468 >            assertEquals(0, p.getCompletedTaskCount());
469          }
470 +        assertEquals(1 + TASKS, p.getTaskCount());
471 +        assertEquals(1 + TASKS, p.getCompletedTaskCount());
472      }
473  
474      /**
475       * getThreadFactory returns factory in constructor if not set
476       */
477      public void testGetThreadFactory() throws InterruptedException {
478 <        ThreadFactory tf = new SimpleThreadFactory();
479 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1, tf);
480 <        assertSame(tf, p.getThreadFactory());
481 <        joinPool(p);
478 >        final ThreadFactory threadFactory = new SimpleThreadFactory();
479 >        final ScheduledThreadPoolExecutor p =
480 >            new ScheduledThreadPoolExecutor(1, threadFactory);
481 >        try (PoolCleaner cleaner = cleaner(p)) {
482 >            assertSame(threadFactory, p.getThreadFactory());
483 >        }
484      }
485  
486      /**
487       * setThreadFactory sets the thread factory returned by getThreadFactory
488       */
489      public void testSetThreadFactory() throws InterruptedException {
490 <        ThreadFactory tf = new SimpleThreadFactory();
491 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
492 <        p.setThreadFactory(tf);
493 <        assertSame(tf, p.getThreadFactory());
494 <        joinPool(p);
490 >        ThreadFactory threadFactory = new SimpleThreadFactory();
491 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
492 >        try (PoolCleaner cleaner = cleaner(p)) {
493 >            p.setThreadFactory(threadFactory);
494 >            assertSame(threadFactory, p.getThreadFactory());
495 >        }
496      }
497  
498      /**
499       * setThreadFactory(null) throws NPE
500       */
501      public void testSetThreadFactoryNull() throws InterruptedException {
502 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
503 <        try {
504 <            p.setThreadFactory(null);
505 <            shouldThrow();
506 <        } catch (NullPointerException success) {
507 <        } finally {
457 <            joinPool(p);
502 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
503 >        try (PoolCleaner cleaner = cleaner(p)) {
504 >            try {
505 >                p.setThreadFactory(null);
506 >                shouldThrow();
507 >            } catch (NullPointerException success) {}
508          }
509      }
510  
511      /**
512 <     * isShutDown is false before shutdown, true after
512 >     * The default rejected execution handler is AbortPolicy.
513       */
514 <    public void testIsShutdown() {
515 <
516 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
517 <        try {
518 <            assertFalse(p.isShutdown());
469 <        }
470 <        finally {
471 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
514 >    public void testDefaultRejectedExecutionHandler() {
515 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
516 >        try (PoolCleaner cleaner = cleaner(p)) {
517 >            assertTrue(p.getRejectedExecutionHandler()
518 >                       instanceof ThreadPoolExecutor.AbortPolicy);
519          }
473        assertTrue(p.isShutdown());
520      }
521  
522 +    /**
523 +     * isShutdown is false before shutdown, true after
524 +     */
525 +    public void testIsShutdown() {
526 +        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
527 +        assertFalse(p.isShutdown());
528 +        try (PoolCleaner cleaner = cleaner(p)) {
529 +            try {
530 +                p.shutdown();
531 +                assertTrue(p.isShutdown());
532 +            } catch (SecurityException ok) {}
533 +        }
534 +    }
535  
536      /**
537       * isTerminated is false before termination, true after
538       */
539      public void testIsTerminated() throws InterruptedException {
540          final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
541 <        final CountDownLatch threadStarted = new CountDownLatch(1);
542 <        final CountDownLatch done = new CountDownLatch(1);
543 <        assertFalse(p.isTerminated());
544 <        try {
541 >        try (PoolCleaner cleaner = cleaner(p)) {
542 >            final CountDownLatch threadStarted = new CountDownLatch(1);
543 >            final CountDownLatch done = new CountDownLatch(1);
544 >            assertFalse(p.isTerminated());
545              p.execute(new CheckedRunnable() {
546                  public void realRun() throws InterruptedException {
547                      assertFalse(p.isTerminated());
548                      threadStarted.countDown();
549 <                    done.await();
549 >                    await(done);
550                  }});
551 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
551 >            await(threadStarted);
552              assertFalse(p.isTerminating());
553              done.countDown();
495        } finally {
554              try { p.shutdown(); } catch (SecurityException ok) { return; }
555 +            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
556 +            assertTrue(p.isTerminated());
557          }
498        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
499        assertTrue(p.isTerminated());
558      }
559  
560      /**
# Line 506 | Line 564 | public class ScheduledExecutorTest exten
564          final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
565          final CountDownLatch threadStarted = new CountDownLatch(1);
566          final CountDownLatch done = new CountDownLatch(1);
567 <        try {
567 >        try (PoolCleaner cleaner = cleaner(p)) {
568              assertFalse(p.isTerminating());
569              p.execute(new CheckedRunnable() {
570                  public void realRun() throws InterruptedException {
571                      assertFalse(p.isTerminating());
572                      threadStarted.countDown();
573 <                    done.await();
573 >                    await(done);
574                  }});
575 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
575 >            await(threadStarted);
576              assertFalse(p.isTerminating());
577              done.countDown();
520        } finally {
578              try { p.shutdown(); } catch (SecurityException ok) { return; }
579 +            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
580 +            assertTrue(p.isTerminated());
581 +            assertFalse(p.isTerminating());
582          }
523        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
524        assertTrue(p.isTerminated());
525        assertFalse(p.isTerminating());
583      }
584  
585      /**
586       * getQueue returns the work queue, which contains queued tasks
587       */
588      public void testGetQueue() throws InterruptedException {
532        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
533        final CountDownLatch threadStarted = new CountDownLatch(1);
589          final CountDownLatch done = new CountDownLatch(1);
590 <        try {
590 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
591 >        try (PoolCleaner cleaner = cleaner(p, done)) {
592 >            final CountDownLatch threadStarted = new CountDownLatch(1);
593              ScheduledFuture[] tasks = new ScheduledFuture[5];
594              for (int i = 0; i < tasks.length; i++) {
595                  Runnable r = new CheckedRunnable() {
596                      public void realRun() throws InterruptedException {
597                          threadStarted.countDown();
598 <                        done.await();
598 >                        await(done);
599                      }};
600                  tasks[i] = p.schedule(r, 1, MILLISECONDS);
601              }
602 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
602 >            await(threadStarted);
603              BlockingQueue<Runnable> q = p.getQueue();
604              assertTrue(q.contains(tasks[tasks.length - 1]));
605              assertFalse(q.contains(tasks[0]));
549        } finally {
550            done.countDown();
551            joinPool(p);
606          }
607      }
608  
# Line 556 | Line 610 | public class ScheduledExecutorTest exten
610       * remove(task) removes queued task, and fails to remove active task
611       */
612      public void testRemove() throws InterruptedException {
559        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
560        ScheduledFuture[] tasks = new ScheduledFuture[5];
561        final CountDownLatch threadStarted = new CountDownLatch(1);
613          final CountDownLatch done = new CountDownLatch(1);
614 <        try {
614 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
615 >        try (PoolCleaner cleaner = cleaner(p, done)) {
616 >            ScheduledFuture[] tasks = new ScheduledFuture[5];
617 >            final CountDownLatch threadStarted = new CountDownLatch(1);
618              for (int i = 0; i < tasks.length; i++) {
619                  Runnable r = new CheckedRunnable() {
620                      public void realRun() throws InterruptedException {
621                          threadStarted.countDown();
622 <                        done.await();
622 >                        await(done);
623                      }};
624                  tasks[i] = p.schedule(r, 1, MILLISECONDS);
625              }
626 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
626 >            await(threadStarted);
627              BlockingQueue<Runnable> q = p.getQueue();
628              assertFalse(p.remove((Runnable)tasks[0]));
629              assertTrue(q.contains((Runnable)tasks[4]));
# Line 580 | Line 634 | public class ScheduledExecutorTest exten
634              assertTrue(q.contains((Runnable)tasks[3]));
635              assertTrue(p.remove((Runnable)tasks[3]));
636              assertFalse(q.contains((Runnable)tasks[3]));
583        } finally {
584            done.countDown();
585            joinPool(p);
637          }
638      }
639  
640      /**
641 <     * purge removes cancelled tasks from the queue
641 >     * purge eventually removes cancelled tasks from the queue
642       */
643      public void testPurge() throws InterruptedException {
644 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
645 <        ScheduledFuture[] tasks = new ScheduledFuture[5];
646 <        for (int i = 0; i < tasks.length; i++) {
647 <            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
648 <        }
649 <        try {
644 >        final ScheduledFuture[] tasks = new ScheduledFuture[5];
645 >        final Runnable releaser = new Runnable() { public void run() {
646 >            for (ScheduledFuture task : tasks)
647 >                if (task != null) task.cancel(true); }};
648 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
649 >        try (PoolCleaner cleaner = cleaner(p, releaser)) {
650 >            for (int i = 0; i < tasks.length; i++)
651 >                tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
652 >                                      LONG_DELAY_MS, MILLISECONDS);
653              int max = tasks.length;
654              if (tasks[4].cancel(true)) --max;
655              if (tasks[3].cancel(true)) --max;
656              // There must eventually be an interference-free point at
657              // which purge will not fail. (At worst, when queue is empty.)
658 <            int k;
659 <            for (k = 0; k < SMALL_DELAY_MS; ++k) {
658 >            long startTime = System.nanoTime();
659 >            do {
660                  p.purge();
661                  long count = p.getTaskCount();
662 <                if (count >= 0 && count <= max)
663 <                    break;
664 <                delay(1);
665 <            }
612 <            assertTrue(k < SMALL_DELAY_MS);
613 <        } finally {
614 <            for (ScheduledFuture task : tasks)
615 <                task.cancel(true);
616 <            joinPool(p);
662 >                if (count == max)
663 >                    return;
664 >            } while (millisElapsedSince(startTime) < LONG_DELAY_MS);
665 >            fail("Purge failed to remove cancelled tasks");
666          }
667      }
668  
669      /**
670 <     * shutDownNow returns a list containing tasks that were not run
671 <     */
672 <    public void testShutDownNow() throws InterruptedException {
673 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
674 <        for (int i = 0; i < 5; i++)
675 <            p.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
676 <        List l;
670 >     * shutdownNow returns a list containing tasks that were not run,
671 >     * and those tasks are drained from the queue
672 >     */
673 >    public void testShutdownNow() throws InterruptedException {
674 >        final int poolSize = 2;
675 >        final int count = 5;
676 >        final AtomicInteger ran = new AtomicInteger(0);
677 >        final ScheduledThreadPoolExecutor p =
678 >            new ScheduledThreadPoolExecutor(poolSize);
679 >        final CountDownLatch threadsStarted = new CountDownLatch(poolSize);
680 >        Runnable waiter = new CheckedRunnable() { public void realRun() {
681 >            threadsStarted.countDown();
682 >            try {
683 >                MILLISECONDS.sleep(2 * LONG_DELAY_MS);
684 >            } catch (InterruptedException success) {}
685 >            ran.getAndIncrement();
686 >        }};
687 >        for (int i = 0; i < count; i++)
688 >            p.execute(waiter);
689 >        await(threadsStarted);
690 >        assertEquals(poolSize, p.getActiveCount());
691 >        assertEquals(0, p.getCompletedTaskCount());
692 >        final List<Runnable> queuedTasks;
693          try {
694 <            l = p.shutdownNow();
694 >            queuedTasks = p.shutdownNow();
695          } catch (SecurityException ok) {
696 <            return;
696 >            return; // Allowed in case test doesn't have privs
697          }
698          assertTrue(p.isShutdown());
699 <        assertTrue(l.size() > 0 && l.size() <= 5);
700 <        joinPool(p);
699 >        assertTrue(p.getQueue().isEmpty());
700 >        assertEquals(count - poolSize, queuedTasks.size());
701 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
702 >        assertTrue(p.isTerminated());
703 >        assertEquals(poolSize, ran.get());
704 >        assertEquals(poolSize, p.getCompletedTaskCount());
705      }
706  
707      /**
708 <     * In default setting, shutdown cancels periodic but not delayed
709 <     * tasks at shutdown
708 >     * shutdownNow returns a list containing tasks that were not run,
709 >     * and those tasks are drained from the queue
710       */
711 <    public void testShutDown1() throws InterruptedException {
712 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
713 <        assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
714 <        assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
715 <
716 <        ScheduledFuture[] tasks = new ScheduledFuture[5];
717 <        for (int i = 0; i < tasks.length; i++)
718 <            tasks[i] = p.schedule(new NoOpRunnable(),
719 <                                  SHORT_DELAY_MS, MILLISECONDS);
720 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
721 <        BlockingQueue<Runnable> q = p.getQueue();
722 <        for (ScheduledFuture task : tasks) {
723 <            assertFalse(task.isDone());
724 <            assertFalse(task.isCancelled());
725 <            assertTrue(q.contains(task));
711 >    public void testShutdownNow_delayedTasks() throws InterruptedException {
712 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
713 >        List<ScheduledFuture> tasks = new ArrayList<>();
714 >        for (int i = 0; i < 3; i++) {
715 >            Runnable r = new NoOpRunnable();
716 >            tasks.add(p.schedule(r, 9, SECONDS));
717 >            tasks.add(p.scheduleAtFixedRate(r, 9, 9, SECONDS));
718 >            tasks.add(p.scheduleWithFixedDelay(r, 9, 9, SECONDS));
719 >        }
720 >        if (testImplementationDetails)
721 >            assertEquals(new HashSet(tasks), new HashSet(p.getQueue()));
722 >        final List<Runnable> queuedTasks;
723 >        try {
724 >            queuedTasks = p.shutdownNow();
725 >        } catch (SecurityException ok) {
726 >            return; // Allowed in case test doesn't have privs
727          }
728          assertTrue(p.isShutdown());
729 <        assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
730 <        assertTrue(p.isTerminated());
729 >        assertTrue(p.getQueue().isEmpty());
730 >        if (testImplementationDetails)
731 >            assertEquals(new HashSet(tasks), new HashSet(queuedTasks));
732 >        assertEquals(tasks.size(), queuedTasks.size());
733          for (ScheduledFuture task : tasks) {
734 <            assertTrue(task.isDone());
734 >            assertFalse(task.isDone());
735              assertFalse(task.isCancelled());
736          }
737 +        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
738 +        assertTrue(p.isTerminated());
739      }
740  
667
741      /**
742 <     * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false,
743 <     * delayed tasks are cancelled at shutdown
744 <     */
745 <    public void testShutDown2() throws InterruptedException {
746 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
747 <        p.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
748 <        assertFalse(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
749 <        assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
750 <        ScheduledFuture[] tasks = new ScheduledFuture[5];
751 <        for (int i = 0; i < tasks.length; i++)
752 <            tasks[i] = p.schedule(new NoOpRunnable(),
753 <                                  SHORT_DELAY_MS, MILLISECONDS);
754 <        BlockingQueue q = p.getQueue();
755 <        assertEquals(tasks.length, q.size());
756 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
757 <        assertTrue(p.isShutdown());
742 >     * By default, periodic tasks are cancelled at shutdown.
743 >     * By default, delayed tasks keep running after shutdown.
744 >     * Check that changing the default values work:
745 >     * - setExecuteExistingDelayedTasksAfterShutdownPolicy
746 >     * - setContinueExistingPeriodicTasksAfterShutdownPolicy
747 >     */
748 >    public void testShutdown_cancellation() throws Exception {
749 >        final int poolSize = 6;
750 >        final ScheduledThreadPoolExecutor p
751 >            = new ScheduledThreadPoolExecutor(poolSize);
752 >        final BlockingQueue<Runnable> q = p.getQueue();
753 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
754 >        final boolean effectiveDelayedPolicy;
755 >        final boolean effectivePeriodicPolicy;
756 >        final boolean effectiveRemovePolicy;
757 >
758 >        if (rnd.nextBoolean())
759 >            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(
760 >                effectiveDelayedPolicy = rnd.nextBoolean());
761 >        else
762 >            effectiveDelayedPolicy = true;
763 >        assertEquals(effectiveDelayedPolicy,
764 >                     p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
765 >
766 >        if (rnd.nextBoolean())
767 >            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(
768 >                effectivePeriodicPolicy = rnd.nextBoolean());
769 >        else
770 >            effectivePeriodicPolicy = false;
771 >        assertEquals(effectivePeriodicPolicy,
772 >                     p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
773 >
774 >        if (rnd.nextBoolean())
775 >            p.setRemoveOnCancelPolicy(
776 >                effectiveRemovePolicy = rnd.nextBoolean());
777 >        else
778 >            effectiveRemovePolicy = false;
779 >        assertEquals(effectiveRemovePolicy,
780 >                     p.getRemoveOnCancelPolicy());
781 >
782 >        final boolean periodicTasksContinue = effectivePeriodicPolicy && rnd.nextBoolean();
783 >
784 >        // Strategy: Wedge the pool with one wave of "blocker" tasks,
785 >        // then add a second wave that waits in the queue until unblocked.
786 >        final AtomicInteger ran = new AtomicInteger(0);
787 >        final CountDownLatch poolBlocked = new CountDownLatch(poolSize);
788 >        final CountDownLatch unblock = new CountDownLatch(1);
789 >        final RuntimeException exception = new RuntimeException();
790 >
791 >        class Task implements Runnable {
792 >            public void run() {
793 >                try {
794 >                    ran.getAndIncrement();
795 >                    poolBlocked.countDown();
796 >                    await(unblock);
797 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
798 >            }
799 >        }
800 >
801 >        class PeriodicTask extends Task {
802 >            PeriodicTask(int rounds) { this.rounds = rounds; }
803 >            int rounds;
804 >            public void run() {
805 >                if (--rounds == 0) super.run();
806 >                // throw exception to surely terminate this periodic task,
807 >                // but in a separate execution and in a detectable way.
808 >                if (rounds == -1) throw exception;
809 >            }
810 >        }
811 >
812 >        Runnable task = new Task();
813 >
814 >        List<Future<?>> immediates = new ArrayList<>();
815 >        List<Future<?>> delayeds   = new ArrayList<>();
816 >        List<Future<?>> periodics  = new ArrayList<>();
817 >
818 >        immediates.add(p.submit(task));
819 >        delayeds.add(p.schedule(task, 1, MILLISECONDS));
820 >        for (int rounds : new int[] { 1, 2 }) {
821 >            periodics.add(p.scheduleAtFixedRate(
822 >                              new PeriodicTask(rounds), 1, 1, MILLISECONDS));
823 >            periodics.add(p.scheduleWithFixedDelay(
824 >                              new PeriodicTask(rounds), 1, 1, MILLISECONDS));
825 >        }
826 >
827 >        await(poolBlocked);
828 >
829 >        assertEquals(poolSize, ran.get());
830 >        assertEquals(poolSize, p.getActiveCount());
831          assertTrue(q.isEmpty());
832 <        assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
833 <        assertTrue(p.isTerminated());
834 <        for (ScheduledFuture task : tasks) {
835 <            assertTrue(task.isDone());
836 <            assertTrue(task.isCancelled());
832 >
833 >        // Add second wave of tasks.
834 >        immediates.add(p.submit(task));
835 >        long delay_ms = effectiveDelayedPolicy ? 1 : LONG_DELAY_MS;
836 >        delayeds.add(p.schedule(task, delay_ms, MILLISECONDS));
837 >        for (int rounds : new int[] { 1, 2 }) {
838 >            periodics.add(p.scheduleAtFixedRate(
839 >                              new PeriodicTask(rounds), 1, 1, MILLISECONDS));
840 >            periodics.add(p.scheduleWithFixedDelay(
841 >                              new PeriodicTask(rounds), 1, 1, MILLISECONDS));
842          }
692    }
843  
844 <    /**
845 <     * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false,
846 <     * periodic tasks are cancelled at shutdown
847 <     */
848 <    public void testShutDown3() throws InterruptedException {
849 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
850 <        assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
851 <        assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
852 <        p.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
703 <        assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
704 <        assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
705 <        ScheduledFuture task =
706 <            p.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, MILLISECONDS);
844 >        assertEquals(poolSize, q.size());
845 >        assertEquals(poolSize, ran.get());
846 >
847 >        immediates.forEach(
848 >            f -> assertTrue(((ScheduledFuture)f).getDelay(NANOSECONDS) <= 0L));
849 >
850 >        Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream())
851 >            .forEach(f -> assertFalse(f.isDone()));
852 >
853          try { p.shutdown(); } catch (SecurityException ok) { return; }
854          assertTrue(p.isShutdown());
855 <        BlockingQueue q = p.getQueue();
856 <        assertTrue(p.getQueue().isEmpty());
711 <        assertTrue(task.isDone());
712 <        assertTrue(task.isCancelled());
713 <        assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
714 <        assertTrue(p.isTerminated());
715 <    }
855 >        assertTrue(p.isTerminating());
856 >        assertFalse(p.isTerminated());
857  
858 <    /**
859 <     * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true,
860 <     * periodic tasks are not cancelled at shutdown
861 <     */
862 <    public void testShutDown4() throws InterruptedException {
863 <        ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
864 <        final CountDownLatch counter = new CountDownLatch(2);
865 <        try {
866 <            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
867 <            assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
868 <            assertTrue(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
869 <            final Runnable r = new CheckedRunnable() {
870 <                public void realRun() {
871 <                    counter.countDown();
872 <                }};
873 <            ScheduledFuture task =
874 <                p.scheduleAtFixedRate(r, 1, 1, MILLISECONDS);
875 <            assertFalse(task.isDone());
876 <            assertFalse(task.isCancelled());
877 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
878 <            assertFalse(task.isCancelled());
879 <            assertFalse(p.isTerminated());
880 <            assertTrue(p.isShutdown());
881 <            assertTrue(counter.await(SMALL_DELAY_MS, MILLISECONDS));
882 <            assertFalse(task.isCancelled());
883 <            assertTrue(task.cancel(false));
884 <            assertTrue(task.isDone());
885 <            assertTrue(task.isCancelled());
886 <            assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
887 <            assertTrue(p.isTerminated());
888 <        }
889 <        finally {
890 <            joinPool(p);
858 >        if (rnd.nextBoolean())
859 >            assertThrows(
860 >                RejectedExecutionException.class,
861 >                () -> p.submit(task),
862 >                () -> p.schedule(task, 1, SECONDS),
863 >                () -> p.scheduleAtFixedRate(
864 >                    new PeriodicTask(1), 1, 1, SECONDS),
865 >                () -> p.scheduleWithFixedDelay(
866 >                    new PeriodicTask(2), 1, 1, SECONDS));
867 >
868 >        assertTrue(q.contains(immediates.get(1)));
869 >        assertTrue(!effectiveDelayedPolicy
870 >                   ^ q.contains(delayeds.get(1)));
871 >        assertTrue(!effectivePeriodicPolicy
872 >                   ^ q.containsAll(periodics.subList(4, 8)));
873 >
874 >        immediates.forEach(f -> assertFalse(f.isDone()));
875 >
876 >        assertFalse(delayeds.get(0).isDone());
877 >        if (effectiveDelayedPolicy)
878 >            assertFalse(delayeds.get(1).isDone());
879 >        else
880 >            assertTrue(delayeds.get(1).isCancelled());
881 >
882 >        if (effectivePeriodicPolicy)
883 >            periodics.forEach(
884 >                f -> {
885 >                    assertFalse(f.isDone());
886 >                    if (!periodicTasksContinue) {
887 >                        assertTrue(f.cancel(false));
888 >                        assertTrue(f.isCancelled());
889 >                    }
890 >                });
891 >        else {
892 >            periodics.subList(0, 4).forEach(f -> assertFalse(f.isDone()));
893 >            periodics.subList(4, 8).forEach(f -> assertTrue(f.isCancelled()));
894          }
895 +
896 +        unblock.countDown();    // Release all pool threads
897 +
898 +        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
899 +        assertFalse(p.isTerminating());
900 +        assertTrue(p.isTerminated());
901 +
902 +        assertTrue(q.isEmpty());
903 +
904 +        Stream.of(immediates, delayeds, periodics).flatMap(c -> c.stream())
905 +            .forEach(f -> assertTrue(f.isDone()));
906 +
907 +        for (Future<?> f : immediates) assertNull(f.get());
908 +
909 +        assertNull(delayeds.get(0).get());
910 +        if (effectiveDelayedPolicy)
911 +            assertNull(delayeds.get(1).get());
912 +        else
913 +            assertTrue(delayeds.get(1).isCancelled());
914 +
915 +        if (periodicTasksContinue)
916 +            periodics.forEach(
917 +                f -> {
918 +                    try { f.get(); }
919 +                    catch (ExecutionException success) {
920 +                        assertSame(exception, success.getCause());
921 +                    }
922 +                    catch (Throwable fail) { threadUnexpectedException(fail); }
923 +                });
924 +        else
925 +            periodics.forEach(f -> assertTrue(f.isCancelled()));
926 +
927 +        assertEquals(poolSize + 1
928 +                     + (effectiveDelayedPolicy ? 1 : 0)
929 +                     + (periodicTasksContinue ? 4 : 0),
930 +                     ran.get());
931      }
932  
933      /**
934       * completed submit of callable returns result
935       */
936      public void testSubmitCallable() throws Exception {
937 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
938 <        try {
937 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
938 >        try (PoolCleaner cleaner = cleaner(e)) {
939              Future<String> future = e.submit(new StringTask());
940              String result = future.get();
941              assertSame(TEST_STRING, result);
762        } finally {
763            joinPool(e);
942          }
943      }
944  
# Line 768 | Line 946 | public class ScheduledExecutorTest exten
946       * completed submit of runnable returns successfully
947       */
948      public void testSubmitRunnable() throws Exception {
949 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
950 <        try {
949 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
950 >        try (PoolCleaner cleaner = cleaner(e)) {
951              Future<?> future = e.submit(new NoOpRunnable());
952              future.get();
953              assertTrue(future.isDone());
776        } finally {
777            joinPool(e);
954          }
955      }
956  
# Line 782 | Line 958 | public class ScheduledExecutorTest exten
958       * completed submit of (runnable, result) returns result
959       */
960      public void testSubmitRunnable2() throws Exception {
961 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
962 <        try {
961 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
962 >        try (PoolCleaner cleaner = cleaner(e)) {
963              Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
964              String result = future.get();
965              assertSame(TEST_STRING, result);
790        } finally {
791            joinPool(e);
966          }
967      }
968  
# Line 796 | Line 970 | public class ScheduledExecutorTest exten
970       * invokeAny(null) throws NPE
971       */
972      public void testInvokeAny1() throws Exception {
973 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
974 <        try {
975 <            e.invokeAny(null);
976 <            shouldThrow();
977 <        } catch (NullPointerException success) {
978 <        } finally {
805 <            joinPool(e);
973 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
974 >        try (PoolCleaner cleaner = cleaner(e)) {
975 >            try {
976 >                e.invokeAny(null);
977 >                shouldThrow();
978 >            } catch (NullPointerException success) {}
979          }
980      }
981  
# Line 810 | Line 983 | public class ScheduledExecutorTest exten
983       * invokeAny(empty collection) throws IAE
984       */
985      public void testInvokeAny2() throws Exception {
986 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
987 <        try {
988 <            e.invokeAny(new ArrayList<Callable<String>>());
989 <            shouldThrow();
990 <        } catch (IllegalArgumentException success) {
991 <        } finally {
819 <            joinPool(e);
986 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
987 >        try (PoolCleaner cleaner = cleaner(e)) {
988 >            try {
989 >                e.invokeAny(new ArrayList<Callable<String>>());
990 >                shouldThrow();
991 >            } catch (IllegalArgumentException success) {}
992          }
993      }
994  
# Line 825 | Line 997 | public class ScheduledExecutorTest exten
997       */
998      public void testInvokeAny3() throws Exception {
999          CountDownLatch latch = new CountDownLatch(1);
1000 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1001 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1002 <        l.add(latchAwaitingStringTask(latch));
1003 <        l.add(null);
1004 <        try {
1005 <            e.invokeAny(l);
1006 <            shouldThrow();
1007 <        } catch (NullPointerException success) {
1008 <        } finally {
1000 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1001 >        try (PoolCleaner cleaner = cleaner(e)) {
1002 >            List<Callable<String>> l = new ArrayList<>();
1003 >            l.add(latchAwaitingStringTask(latch));
1004 >            l.add(null);
1005 >            try {
1006 >                e.invokeAny(l);
1007 >                shouldThrow();
1008 >            } catch (NullPointerException success) {}
1009              latch.countDown();
838            joinPool(e);
1010          }
1011      }
1012  
# Line 843 | Line 1014 | public class ScheduledExecutorTest exten
1014       * invokeAny(c) throws ExecutionException if no task completes
1015       */
1016      public void testInvokeAny4() throws Exception {
1017 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1018 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1019 <        l.add(new NPETask());
1020 <        try {
1021 <            e.invokeAny(l);
1022 <            shouldThrow();
1023 <        } catch (ExecutionException success) {
1024 <            assertTrue(success.getCause() instanceof NullPointerException);
1025 <        } finally {
1026 <            joinPool(e);
1017 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1018 >        try (PoolCleaner cleaner = cleaner(e)) {
1019 >            List<Callable<String>> l = new ArrayList<>();
1020 >            l.add(new NPETask());
1021 >            try {
1022 >                e.invokeAny(l);
1023 >                shouldThrow();
1024 >            } catch (ExecutionException success) {
1025 >                assertTrue(success.getCause() instanceof NullPointerException);
1026 >            }
1027          }
1028      }
1029  
# Line 860 | Line 1031 | public class ScheduledExecutorTest exten
1031       * invokeAny(c) returns result of some task
1032       */
1033      public void testInvokeAny5() throws Exception {
1034 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1035 <        try {
1036 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1034 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1035 >        try (PoolCleaner cleaner = cleaner(e)) {
1036 >            List<Callable<String>> l = new ArrayList<>();
1037              l.add(new StringTask());
1038              l.add(new StringTask());
1039              String result = e.invokeAny(l);
1040              assertSame(TEST_STRING, result);
870        } finally {
871            joinPool(e);
1041          }
1042      }
1043  
# Line 876 | Line 1045 | public class ScheduledExecutorTest exten
1045       * invokeAll(null) throws NPE
1046       */
1047      public void testInvokeAll1() throws Exception {
1048 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1049 <        try {
1050 <            e.invokeAll(null);
1051 <            shouldThrow();
1052 <        } catch (NullPointerException success) {
1053 <        } finally {
885 <            joinPool(e);
1048 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1049 >        try (PoolCleaner cleaner = cleaner(e)) {
1050 >            try {
1051 >                e.invokeAll(null);
1052 >                shouldThrow();
1053 >            } catch (NullPointerException success) {}
1054          }
1055      }
1056  
# Line 890 | Line 1058 | public class ScheduledExecutorTest exten
1058       * invokeAll(empty collection) returns empty collection
1059       */
1060      public void testInvokeAll2() throws Exception {
1061 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1062 <        try {
1061 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1062 >        try (PoolCleaner cleaner = cleaner(e)) {
1063              List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
1064              assertTrue(r.isEmpty());
897        } finally {
898            joinPool(e);
1065          }
1066      }
1067  
# Line 903 | Line 1069 | public class ScheduledExecutorTest exten
1069       * invokeAll(c) throws NPE if c has null elements
1070       */
1071      public void testInvokeAll3() throws Exception {
1072 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1073 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1074 <        l.add(new StringTask());
1075 <        l.add(null);
1076 <        try {
1077 <            e.invokeAll(l);
1078 <            shouldThrow();
1079 <        } catch (NullPointerException success) {
1080 <        } finally {
915 <            joinPool(e);
1072 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1073 >        try (PoolCleaner cleaner = cleaner(e)) {
1074 >            List<Callable<String>> l = new ArrayList<>();
1075 >            l.add(new StringTask());
1076 >            l.add(null);
1077 >            try {
1078 >                e.invokeAll(l);
1079 >                shouldThrow();
1080 >            } catch (NullPointerException success) {}
1081          }
1082      }
1083  
# Line 920 | Line 1085 | public class ScheduledExecutorTest exten
1085       * get of invokeAll(c) throws exception on failed task
1086       */
1087      public void testInvokeAll4() throws Exception {
1088 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1089 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1090 <        l.add(new NPETask());
1091 <        List<Future<String>> futures = e.invokeAll(l);
1092 <        assertEquals(1, futures.size());
1093 <        try {
1094 <            futures.get(0).get();
1095 <            shouldThrow();
1096 <        } catch (ExecutionException success) {
1097 <            assertTrue(success.getCause() instanceof NullPointerException);
1098 <        } finally {
1099 <            joinPool(e);
1088 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1089 >        try (PoolCleaner cleaner = cleaner(e)) {
1090 >            List<Callable<String>> l = new ArrayList<>();
1091 >            l.add(new NPETask());
1092 >            List<Future<String>> futures = e.invokeAll(l);
1093 >            assertEquals(1, futures.size());
1094 >            try {
1095 >                futures.get(0).get();
1096 >                shouldThrow();
1097 >            } catch (ExecutionException success) {
1098 >                assertTrue(success.getCause() instanceof NullPointerException);
1099 >            }
1100          }
1101      }
1102  
# Line 939 | Line 1104 | public class ScheduledExecutorTest exten
1104       * invokeAll(c) returns results of all completed tasks
1105       */
1106      public void testInvokeAll5() throws Exception {
1107 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1108 <        try {
1109 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1107 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1108 >        try (PoolCleaner cleaner = cleaner(e)) {
1109 >            List<Callable<String>> l = new ArrayList<>();
1110              l.add(new StringTask());
1111              l.add(new StringTask());
1112              List<Future<String>> futures = e.invokeAll(l);
1113              assertEquals(2, futures.size());
1114              for (Future<String> future : futures)
1115                  assertSame(TEST_STRING, future.get());
951        } finally {
952            joinPool(e);
1116          }
1117      }
1118  
# Line 957 | Line 1120 | public class ScheduledExecutorTest exten
1120       * timed invokeAny(null) throws NPE
1121       */
1122      public void testTimedInvokeAny1() throws Exception {
1123 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1124 <        try {
1125 <            e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1126 <            shouldThrow();
1127 <        } catch (NullPointerException success) {
1128 <        } finally {
966 <            joinPool(e);
1123 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1124 >        try (PoolCleaner cleaner = cleaner(e)) {
1125 >            try {
1126 >                e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1127 >                shouldThrow();
1128 >            } catch (NullPointerException success) {}
1129          }
1130      }
1131  
# Line 971 | Line 1133 | public class ScheduledExecutorTest exten
1133       * timed invokeAny(,,null) throws NPE
1134       */
1135      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1136 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1137 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1138 <        l.add(new StringTask());
1139 <        try {
1140 <            e.invokeAny(l, MEDIUM_DELAY_MS, null);
1141 <            shouldThrow();
1142 <        } catch (NullPointerException success) {
1143 <        } finally {
982 <            joinPool(e);
1136 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1137 >        try (PoolCleaner cleaner = cleaner(e)) {
1138 >            List<Callable<String>> l = new ArrayList<>();
1139 >            l.add(new StringTask());
1140 >            try {
1141 >                e.invokeAny(l, MEDIUM_DELAY_MS, null);
1142 >                shouldThrow();
1143 >            } catch (NullPointerException success) {}
1144          }
1145      }
1146  
# Line 987 | Line 1148 | public class ScheduledExecutorTest exten
1148       * timed invokeAny(empty collection) throws IAE
1149       */
1150      public void testTimedInvokeAny2() throws Exception {
1151 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1152 <        try {
1153 <            e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1154 <            shouldThrow();
1155 <        } catch (IllegalArgumentException success) {
1156 <        } finally {
996 <            joinPool(e);
1151 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1152 >        try (PoolCleaner cleaner = cleaner(e)) {
1153 >            try {
1154 >                e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1155 >                shouldThrow();
1156 >            } catch (IllegalArgumentException success) {}
1157          }
1158      }
1159  
# Line 1002 | Line 1162 | public class ScheduledExecutorTest exten
1162       */
1163      public void testTimedInvokeAny3() throws Exception {
1164          CountDownLatch latch = new CountDownLatch(1);
1165 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1166 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1167 <        l.add(latchAwaitingStringTask(latch));
1168 <        l.add(null);
1169 <        try {
1170 <            e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1171 <            shouldThrow();
1172 <        } catch (NullPointerException success) {
1173 <        } finally {
1165 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1166 >        try (PoolCleaner cleaner = cleaner(e)) {
1167 >            List<Callable<String>> l = new ArrayList<>();
1168 >            l.add(latchAwaitingStringTask(latch));
1169 >            l.add(null);
1170 >            try {
1171 >                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1172 >                shouldThrow();
1173 >            } catch (NullPointerException success) {}
1174              latch.countDown();
1015            joinPool(e);
1175          }
1176      }
1177  
# Line 1020 | Line 1179 | public class ScheduledExecutorTest exten
1179       * timed invokeAny(c) throws ExecutionException if no task completes
1180       */
1181      public void testTimedInvokeAny4() throws Exception {
1182 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1183 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1184 <        l.add(new NPETask());
1185 <        try {
1186 <            e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1187 <            shouldThrow();
1188 <        } catch (ExecutionException success) {
1189 <            assertTrue(success.getCause() instanceof NullPointerException);
1190 <        } finally {
1191 <            joinPool(e);
1182 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1183 >        try (PoolCleaner cleaner = cleaner(e)) {
1184 >            long startTime = System.nanoTime();
1185 >            List<Callable<String>> l = new ArrayList<>();
1186 >            l.add(new NPETask());
1187 >            try {
1188 >                e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1189 >                shouldThrow();
1190 >            } catch (ExecutionException success) {
1191 >                assertTrue(success.getCause() instanceof NullPointerException);
1192 >            }
1193 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1194          }
1195      }
1196  
# Line 1037 | Line 1198 | public class ScheduledExecutorTest exten
1198       * timed invokeAny(c) returns result of some task
1199       */
1200      public void testTimedInvokeAny5() throws Exception {
1201 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1202 <        try {
1203 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1201 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1202 >        try (PoolCleaner cleaner = cleaner(e)) {
1203 >            long startTime = System.nanoTime();
1204 >            List<Callable<String>> l = new ArrayList<>();
1205              l.add(new StringTask());
1206              l.add(new StringTask());
1207 <            String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1207 >            String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1208              assertSame(TEST_STRING, result);
1209 <        } finally {
1048 <            joinPool(e);
1209 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1210          }
1211      }
1212  
# Line 1053 | Line 1214 | public class ScheduledExecutorTest exten
1214       * timed invokeAll(null) throws NPE
1215       */
1216      public void testTimedInvokeAll1() throws Exception {
1217 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1218 <        try {
1219 <            e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1220 <            shouldThrow();
1221 <        } catch (NullPointerException success) {
1222 <        } finally {
1062 <            joinPool(e);
1217 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1218 >        try (PoolCleaner cleaner = cleaner(e)) {
1219 >            try {
1220 >                e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1221 >                shouldThrow();
1222 >            } catch (NullPointerException success) {}
1223          }
1224      }
1225  
# Line 1067 | Line 1227 | public class ScheduledExecutorTest exten
1227       * timed invokeAll(,,null) throws NPE
1228       */
1229      public void testTimedInvokeAllNullTimeUnit() throws Exception {
1230 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1231 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1232 <        l.add(new StringTask());
1233 <        try {
1234 <            e.invokeAll(l, MEDIUM_DELAY_MS, null);
1235 <            shouldThrow();
1236 <        } catch (NullPointerException success) {
1237 <        } finally {
1078 <            joinPool(e);
1230 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1231 >        try (PoolCleaner cleaner = cleaner(e)) {
1232 >            List<Callable<String>> l = new ArrayList<>();
1233 >            l.add(new StringTask());
1234 >            try {
1235 >                e.invokeAll(l, MEDIUM_DELAY_MS, null);
1236 >                shouldThrow();
1237 >            } catch (NullPointerException success) {}
1238          }
1239      }
1240  
# Line 1083 | Line 1242 | public class ScheduledExecutorTest exten
1242       * timed invokeAll(empty collection) returns empty collection
1243       */
1244      public void testTimedInvokeAll2() throws Exception {
1245 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1246 <        try {
1247 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1245 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1246 >        try (PoolCleaner cleaner = cleaner(e)) {
1247 >            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(),
1248 >                                                 MEDIUM_DELAY_MS, MILLISECONDS);
1249              assertTrue(r.isEmpty());
1090        } finally {
1091            joinPool(e);
1250          }
1251      }
1252  
# Line 1096 | Line 1254 | public class ScheduledExecutorTest exten
1254       * timed invokeAll(c) throws NPE if c has null elements
1255       */
1256      public void testTimedInvokeAll3() throws Exception {
1257 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1258 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1259 <        l.add(new StringTask());
1260 <        l.add(null);
1261 <        try {
1262 <            e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1263 <            shouldThrow();
1264 <        } catch (NullPointerException success) {
1265 <        } finally {
1108 <            joinPool(e);
1257 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1258 >        try (PoolCleaner cleaner = cleaner(e)) {
1259 >            List<Callable<String>> l = new ArrayList<>();
1260 >            l.add(new StringTask());
1261 >            l.add(null);
1262 >            try {
1263 >                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1264 >                shouldThrow();
1265 >            } catch (NullPointerException success) {}
1266          }
1267      }
1268  
# Line 1113 | Line 1270 | public class ScheduledExecutorTest exten
1270       * get of element of invokeAll(c) throws exception on failed task
1271       */
1272      public void testTimedInvokeAll4() throws Exception {
1273 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1274 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1275 <        l.add(new NPETask());
1276 <        List<Future<String>> futures =
1277 <            e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1278 <        assertEquals(1, futures.size());
1279 <        try {
1280 <            futures.get(0).get();
1281 <            shouldThrow();
1282 <        } catch (ExecutionException success) {
1283 <            assertTrue(success.getCause() instanceof NullPointerException);
1284 <        } finally {
1285 <            joinPool(e);
1273 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1274 >        try (PoolCleaner cleaner = cleaner(e)) {
1275 >            List<Callable<String>> l = new ArrayList<>();
1276 >            l.add(new NPETask());
1277 >            List<Future<String>> futures =
1278 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1279 >            assertEquals(1, futures.size());
1280 >            try {
1281 >                futures.get(0).get();
1282 >                shouldThrow();
1283 >            } catch (ExecutionException success) {
1284 >                assertTrue(success.getCause() instanceof NullPointerException);
1285 >            }
1286          }
1287      }
1288  
# Line 1133 | Line 1290 | public class ScheduledExecutorTest exten
1290       * timed invokeAll(c) returns results of all completed tasks
1291       */
1292      public void testTimedInvokeAll5() throws Exception {
1293 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1294 <        try {
1295 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1293 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1294 >        try (PoolCleaner cleaner = cleaner(e)) {
1295 >            List<Callable<String>> l = new ArrayList<>();
1296              l.add(new StringTask());
1297              l.add(new StringTask());
1298              List<Future<String>> futures =
1299 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1299 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1300              assertEquals(2, futures.size());
1301              for (Future<String> future : futures)
1302                  assertSame(TEST_STRING, future.get());
1146        } finally {
1147            joinPool(e);
1303          }
1304      }
1305  
# Line 1152 | Line 1307 | public class ScheduledExecutorTest exten
1307       * timed invokeAll(c) cancels tasks not completed by timeout
1308       */
1309      public void testTimedInvokeAll6() throws Exception {
1310 <        ExecutorService e = new ScheduledThreadPoolExecutor(2);
1311 <        try {
1312 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1313 <            l.add(new StringTask());
1314 <            l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
1315 <            l.add(new StringTask());
1316 <            List<Future<String>> futures =
1317 <                e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
1318 <            assertEquals(3, futures.size());
1319 <            Iterator<Future<String>> it = futures.iterator();
1320 <            Future<String> f1 = it.next();
1321 <            Future<String> f2 = it.next();
1322 <            Future<String> f3 = it.next();
1323 <            assertTrue(f1.isDone());
1324 <            assertTrue(f2.isDone());
1325 <            assertTrue(f3.isDone());
1326 <            assertFalse(f1.isCancelled());
1327 <            assertTrue(f2.isCancelled());
1328 <        } finally {
1329 <            joinPool(e);
1310 >        for (long timeout = timeoutMillis();;) {
1311 >            final CountDownLatch done = new CountDownLatch(1);
1312 >            final Callable<String> waiter = new CheckedCallable<String>() {
1313 >                public String realCall() {
1314 >                    try { done.await(LONG_DELAY_MS, MILLISECONDS); }
1315 >                    catch (InterruptedException ok) {}
1316 >                    return "1"; }};
1317 >            final ExecutorService p = new ScheduledThreadPoolExecutor(2);
1318 >            try (PoolCleaner cleaner = cleaner(p, done)) {
1319 >                List<Callable<String>> tasks = new ArrayList<>();
1320 >                tasks.add(new StringTask("0"));
1321 >                tasks.add(waiter);
1322 >                tasks.add(new StringTask("2"));
1323 >                long startTime = System.nanoTime();
1324 >                List<Future<String>> futures =
1325 >                    p.invokeAll(tasks, timeout, MILLISECONDS);
1326 >                assertEquals(tasks.size(), futures.size());
1327 >                assertTrue(millisElapsedSince(startTime) >= timeout);
1328 >                for (Future future : futures)
1329 >                    assertTrue(future.isDone());
1330 >                assertTrue(futures.get(1).isCancelled());
1331 >                try {
1332 >                    assertEquals("0", futures.get(0).get());
1333 >                    assertEquals("2", futures.get(2).get());
1334 >                    break;
1335 >                } catch (CancellationException retryWithLongerTimeout) {
1336 >                    timeout *= 2;
1337 >                    if (timeout >= LONG_DELAY_MS / 2)
1338 >                        fail("expected exactly one task to be cancelled");
1339 >                }
1340 >            }
1341          }
1342      }
1343  
1344 +    /**
1345 +     * A fixed delay task with overflowing period should not prevent a
1346 +     * one-shot task from executing.
1347 +     * https://bugs.openjdk.java.net/browse/JDK-8051859
1348 +     */
1349 +    public void testScheduleWithFixedDelay_overflow() throws Exception {
1350 +        final CountDownLatch delayedDone = new CountDownLatch(1);
1351 +        final CountDownLatch immediateDone = new CountDownLatch(1);
1352 +        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
1353 +        try (PoolCleaner cleaner = cleaner(p)) {
1354 +            final Runnable immediate = new Runnable() { public void run() {
1355 +                immediateDone.countDown();
1356 +            }};
1357 +            final Runnable delayed = new Runnable() { public void run() {
1358 +                delayedDone.countDown();
1359 +                p.submit(immediate);
1360 +            }};
1361 +            p.scheduleWithFixedDelay(delayed, 0L, Long.MAX_VALUE, SECONDS);
1362 +            await(delayedDone);
1363 +            await(immediateDone);
1364 +        }
1365 +    }
1366  
1367   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines