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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines