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.29 by jsr166, Tue Dec 1 22:51:44 2009 UTC vs.
Revision 1.86 by jsr166, Sat Mar 25 21:41:10 2017 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines