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.2 by dl, Sun Sep 7 23:50:09 2003 UTC vs.
Revision 1.82 by jsr166, Thu Sep 15 17:31:16 2016 UTC

# Line 1 | Line 1
1   /*
2 < * Written by members of JCP JSR-166 Expert Group and released to the
3 < * public domain. Use, modify, and redistribute this code in any way
4 < * without acknowledgement. Other contributors include Andrew Wright,
5 < * Jeffrey Hayes, Pat Fischer, Mike Judd.
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/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 <
13 < public class ScheduledExecutorTest extends TestCase{
14 <    
15 <    boolean flag = false;
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      }
19    
20
39      public static Test suite() {
40 <        return new TestSuite(ScheduledExecutorTest.class);
40 >        return new TestSuite(ScheduledExecutorTest.class);
41      }
42  
43 <    private static long SHORT_DELAY_MS = 100;
44 <    private static long MEDIUM_DELAY_MS = 1000;
45 <    private static long LONG_DELAY_MS = 10000;
43 >    /**
44 >     * execute successfully executes a runnable
45 >     */
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 >        }
55 >    }
56 >
57 >    /**
58 >     * delayed schedule of callable successfully executes after delay
59 >     */
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() throws Exception {
82 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
83 >        try (PoolCleaner cleaner = cleaner(p)) {
84 >            final long startTime = System.nanoTime();
85 >            final CountDownLatch done = new CountDownLatch(1);
86 >            Runnable task = new CheckedRunnable() {
87 >                public void realRun() {
88 >                    done.countDown();
89 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
90 >                }};
91 >            Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
92 >            await(done);
93 >            assertNull(f.get(LONG_DELAY_MS, MILLISECONDS));
94 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
95 >        }
96 >    }
97 >
98 >    /**
99 >     * scheduleAtFixedRate executes runnable after given initial delay
100 >     */
101 >    public void testSchedule4() throws Exception {
102 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
103 >        try (PoolCleaner cleaner = cleaner(p)) {
104 >            final long startTime = System.nanoTime();
105 >            final CountDownLatch done = new CountDownLatch(1);
106 >            Runnable task = new CheckedRunnable() {
107 >                public void realRun() {
108 >                    done.countDown();
109 >                    assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
110 >                }};
111 >            ScheduledFuture f =
112 >                p.scheduleAtFixedRate(task, timeoutMillis(),
113 >                                      LONG_DELAY_MS, MILLISECONDS);
114 >            await(done);
115 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
116 >            f.cancel(true);
117 >        }
118 >    }
119 >
120 >    /**
121 >     * scheduleWithFixedDelay executes runnable after given initial delay
122 >     */
123 >    public void testSchedule5() throws 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 >     * 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 <    static class MyRunnable implements Runnable {
177 <        volatile boolean waiting = true;
178 <        volatile boolean done = false;
179 <        public void run(){
180 <            try{
181 <                Thread.sleep(SHORT_DELAY_MS);
182 <                waiting = false;
183 <                done = true;
184 <            } catch(Exception e){
176 >    /**
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  
222 <    static class MyCallable implements Callable {
223 <        volatile boolean waiting = true;
224 <        volatile boolean done = false;
225 <        public Object call(){
226 <            try{
227 <                Thread.sleep(SHORT_DELAY_MS);
228 <                waiting = false;
229 <                done = true;
230 <            }catch(Exception e){}
231 <            return Boolean.TRUE;
222 >    /**
223 >     * execute(null) throws NPE
224 >     */
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          }
233      }
234  
235 <    public Runnable newRunnable(){
236 <        return new Runnable(){
237 <                public void run(){
238 <                    try{Thread.sleep(SHORT_DELAY_MS);
239 <                    } catch(Exception e){
240 <                    }
241 <                }
242 <            };
235 >    /**
236 >     * schedule(null) throws NPE
237 >     */
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 >        }
247      }
248  
249 <    public Runnable newNoopRunnable() {
250 <        return new Runnable(){
251 <                public void run(){
252 <                }
253 <            };
249 >    /**
250 >     * execute throws RejectedExecutionException if shutdown
251 >     */
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 >        }
263      }
264  
265      /**
266 <     *  Test to verify execute successfully runs the given Runnable
266 >     * schedule throws RejectedExecutionException if shutdown
267       */
268 <    public void testExecute(){
269 <        try{
270 <            MyRunnable runnable =new MyRunnable();
271 <            ScheduledExecutor one = new ScheduledExecutor(1);
272 <            one.execute(runnable);
273 <            Thread.sleep(SHORT_DELAY_MS/2);
274 <            assertTrue(runnable.waiting);
275 <            one.shutdown();
276 <            try{
277 <                Thread.sleep(MEDIUM_DELAY_MS);
278 <            } catch(InterruptedException e){
279 <                fail("unexpected exception");
280 <            }
281 <            assertFalse(runnable.waiting);
282 <            assertTrue(runnable.done);
283 <            one.shutdown();
268 >    public void testSchedule2_RejectedExecutionException() throws InterruptedException {
269 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
270 >        try (PoolCleaner cleaner = cleaner(p)) {
271 >            try {
272 >                p.shutdown();
273 >                p.schedule(new NoOpCallable(),
274 >                           MEDIUM_DELAY_MS, MILLISECONDS);
275 >                shouldThrow();
276 >            } catch (RejectedExecutionException success) {
277 >            } catch (SecurityException ok) {}
278 >        }
279 >    }
280 >
281 >    /**
282 >     * schedule callable throws RejectedExecutionException if shutdown
283 >     */
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          }
295 <        catch(Exception e){
296 <            fail("unexpected exception");
295 >    }
296 >
297 >    /**
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          }
311      }
312  
313      /**
314 <     *  Test to verify schedule successfully runs the given Callable.
99 <     *  The waiting flag shows that the Callable is not started until
100 <     *  immediately.
314 >     * scheduleWithFixedDelay throws RejectedExecutionException if shutdown
315       */
316 <    public void testSchedule1(){
317 <        try{
318 <            MyCallable callable = new MyCallable();
319 <            ScheduledExecutor one = new ScheduledExecutor(1);
320 <            Future f = one.schedule(callable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
321 <            assertTrue(callable.waiting);
322 <            Thread.sleep(MEDIUM_DELAY_MS);
323 <            assertTrue(callable.done);
324 <            assertEquals(Boolean.TRUE, f.get());
325 <            one.shutdown();
112 <        }catch(RejectedExecutionException e){}
113 <        catch(Exception e){
114 <            fail("unexpected exception");
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          }
327      }
328  
329      /**
330 <     *  Another version of schedule, only using Runnable instead of Callable
330 >     * getActiveCount increases but doesn't overestimate, when a
331 >     * thread becomes active
332       */
333 <    public void testSchedule3(){
334 <        try{
335 <            MyRunnable runnable = new MyRunnable();
336 <            ScheduledExecutor one = new ScheduledExecutor(1);
337 <            one.schedule(runnable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
338 <            Thread.sleep(SHORT_DELAY_MS/2);
339 <            assertTrue(runnable.waiting);
340 <            Thread.sleep(MEDIUM_DELAY_MS);
341 <            assertTrue(runnable.done);
342 <            one.shutdown();
343 <        } catch(Exception e){
344 <            fail("unexpected exception");
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          }
348      }
349 <    
349 >
350      /**
351 <     *  The final version of schedule, using both long, TimeUnit and Runnable
351 >     * getCompletedTaskCount increases, but doesn't overestimate,
352 >     * when tasks complete
353       */
354 <    public void testSchedule4(){
355 <        try{
356 <            MyRunnable runnable = new MyRunnable();
357 <            ScheduledExecutor one = new ScheduledExecutor(1);
358 <            one.schedule(runnable, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
359 <            //      Thread.sleep(505);
360 <            assertTrue(runnable.waiting);
361 <            Thread.sleep(MEDIUM_DELAY_MS);
362 <            assertTrue(runnable.done);
363 <            one.shutdown();
364 <        } catch(Exception e){
365 <            fail("unexpected exception");
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          }
379      }
153    
154  
155    // exception tests
380  
381      /**
382 <     *  Test to verify schedule(Runnable, long) throws RejectedExecutionException
159 <     *  This occurs on an attempt to schedule a task on a shutdown executor
382 >     * getCorePoolSize returns size given in constructor if not otherwise set
383       */
384 <    public void testSchedule1_RejectedExecutionException(){
385 <        try{
386 <            ScheduledExecutor se = new ScheduledExecutor(1);
387 <            se.shutdown();
388 <            se.schedule(new Runnable(){
389 <                    public void run(){}
390 <                }, 10000, TimeUnit.MILLISECONDS);
391 <            fail("shoud throw");
392 <        }catch(RejectedExecutionException e){}    
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(1 + TASKS, p.getTaskCount());
469 >        assertEquals(1 + TASKS, p.getCompletedTaskCount());
470      }
471  
472      /**
473 <     *  Test to verify schedule(Callable, long, TimeUnit) throws RejectedExecutionException
174 <     *  This occurs on an attempt to schedule a task on a shutdown executor
473 >     * getThreadFactory returns factory in constructor if not set
474       */
475 <    public void testSchedule2_RejectedExecutionException(){
476 <        try{
477 <            ScheduledExecutor se = new ScheduledExecutor(1);
478 <            se.shutdown();
479 <            se.schedule(new Callable(){
480 <                    public Object call(){
481 <                        return Boolean.TRUE;
183 <                    }
184 <                }, (long)100, TimeUnit.SECONDS);
185 <            fail("should throw");
186 <        }catch(RejectedExecutionException e){}    
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 <     *  Test to verify schedule(Callable, long) throws RejectedExecutionException
191 <     *  This occurs on an attempt to schedule a task on a shutdown executor
485 >     * setThreadFactory sets the thread factory returned by getThreadFactory
486       */
487 <     public void testSchedule3_RejectedExecutionException(){
488 <        try{
489 <            ScheduledExecutor se = new ScheduledExecutor(1);
490 <            se.shutdown();
491 <            se.schedule(new Callable(){
492 <                    public Object call(){
493 <                        return Boolean.TRUE;
200 <                    }
201 <                },  10000, TimeUnit.MILLISECONDS);
202 <            fail("should throw");
203 <        }catch(RejectedExecutionException e){}    
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 <     *  Test to verify scheduleAtFixedRate(Runnable, long, long, TimeUnit) throws
208 <     *  RejectedExecutionException.
209 <     *  This occurs on an attempt to schedule a task on a shutdown executor
497 >     * setThreadFactory(null) throws NPE
498       */
499 <    public void testScheduleAtFixedRate1_RejectedExecutionException(){
500 <        try{
501 <            ScheduledExecutor se = new ScheduledExecutor(1);
502 <            se.shutdown();
503 <            se.scheduleAtFixedRate(new Runnable(){
504 <                    public void run(){}
505 <                }, 100, 100, TimeUnit.SECONDS);
506 <            fail("should throw");
219 <        }catch(RejectedExecutionException e){}    
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 <    
508 >
509      /**
510 <     *  Test to verify scheduleAtFixedRate(Runnable, long, long, TimeUnit) throws
224 <     *  RejectedExecutionException.
225 <     *  This occurs on an attempt to schedule a task on a shutdown executor
510 >     * isShutdown is false before shutdown, true after
511       */
512 <    public void testScheduleAtFixedRate2_RejectedExecutionException(){
513 <        try{
514 <            ScheduledExecutor se = new ScheduledExecutor(1);
515 <            se.shutdown();
516 <            se.scheduleAtFixedRate(new Runnable(){
517 <                    public void run(){}
518 <                },  1, 100, TimeUnit.SECONDS);
519 <            fail("should throw");
520 <        }catch(RejectedExecutionException e){}    
512 >    public void testIsShutdown() {
513 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
514 >        assertFalse(p.isShutdown());
515 >        try (PoolCleaner cleaner = cleaner(p)) {
516 >            try {
517 >                p.shutdown();
518 >                assertTrue(p.isShutdown());
519 >            } catch (SecurityException ok) {}
520 >        }
521      }
522  
523      /**
524 <     *  Test to verify scheduleWithFixedDelay(Runnable, long, long, TimeUnit) throws
240 <     *  RejectedExecutionException.
241 <     *  This occurs on an attempt to schedule a task on a shutdown executor
524 >     * isTerminated is false before termination, true after
525       */
526 <    public void testScheduleWithFixedDelay1_RejectedExecutionException(){
527 <        try{
528 <            ScheduledExecutor se = new ScheduledExecutor(1);
529 <            se.shutdown();
530 <            se.scheduleWithFixedDelay(new Runnable(){
531 <                    public void run(){}
532 <                }, 100, 100, TimeUnit.SECONDS);
533 <            fail("should throw");
534 <        }catch(RejectedExecutionException e){}    
526 >    public void testIsTerminated() throws InterruptedException {
527 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
528 >        try (PoolCleaner cleaner = cleaner(p)) {
529 >            final CountDownLatch threadStarted = new CountDownLatch(1);
530 >            final CountDownLatch done = new CountDownLatch(1);
531 >            assertFalse(p.isTerminated());
532 >            p.execute(new CheckedRunnable() {
533 >                public void realRun() throws InterruptedException {
534 >                    assertFalse(p.isTerminated());
535 >                    threadStarted.countDown();
536 >                    await(done);
537 >                }});
538 >            await(threadStarted);
539 >            assertFalse(p.isTerminating());
540 >            done.countDown();
541 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
542 >            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
543 >            assertTrue(p.isTerminated());
544 >        }
545      }
546  
547      /**
548 <     *  Test to verify scheduleWithFixedDelay(Runnable, long, long, TimeUnit) throws
256 <     *  RejectedExecutionException.
257 <     *  This occurs on an attempt to schedule a task on a shutdown executor
548 >     * isTerminating is not true when running or when terminated
549       */
550 <     public void testScheduleWithFixedDelay2_RejectedExecutionException(){
551 <        try{
552 <            ScheduledExecutor se = new ScheduledExecutor(1);
553 <            se.shutdown();
554 <            se.scheduleWithFixedDelay(new Runnable(){
555 <                    public void run(){}
556 <                },  1, 100, TimeUnit.SECONDS);
557 <            fail("should throw");
558 <        }catch(RejectedExecutionException e){}    
550 >    public void testIsTerminating() throws InterruptedException {
551 >        final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
552 >        final CountDownLatch threadStarted = new CountDownLatch(1);
553 >        final CountDownLatch done = new CountDownLatch(1);
554 >        try (PoolCleaner cleaner = cleaner(p)) {
555 >            assertFalse(p.isTerminating());
556 >            p.execute(new CheckedRunnable() {
557 >                public void realRun() throws InterruptedException {
558 >                    assertFalse(p.isTerminating());
559 >                    threadStarted.countDown();
560 >                    await(done);
561 >                }});
562 >            await(threadStarted);
563 >            assertFalse(p.isTerminating());
564 >            done.countDown();
565 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
566 >            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
567 >            assertTrue(p.isTerminated());
568 >            assertFalse(p.isTerminating());
569 >        }
570      }
571  
572      /**
573 <     *  Test to verify execute throws RejectedExecutionException
272 <     *  This occurs on an attempt to schedule a task on a shutdown executor
573 >     * getQueue returns the work queue, which contains queued tasks
574       */
575 <    public void testExecute_RejectedExecutionException(){
576 <        try{
577 <            ScheduledExecutor se = new ScheduledExecutor(1);
578 <            se.shutdown();
579 <            se.execute(new Runnable(){
580 <                    public void run(){}
581 <                });
582 <            fail("should throw");
583 <        }catch(RejectedExecutionException e){}    
575 >    public void testGetQueue() throws InterruptedException {
576 >        final CountDownLatch done = new CountDownLatch(1);
577 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
578 >        try (PoolCleaner cleaner = cleaner(p, done)) {
579 >            final CountDownLatch threadStarted = new CountDownLatch(1);
580 >            ScheduledFuture[] tasks = new ScheduledFuture[5];
581 >            for (int i = 0; i < tasks.length; i++) {
582 >                Runnable r = new CheckedRunnable() {
583 >                    public void realRun() throws InterruptedException {
584 >                        threadStarted.countDown();
585 >                        await(done);
586 >                    }};
587 >                tasks[i] = p.schedule(r, 1, MILLISECONDS);
588 >            }
589 >            await(threadStarted);
590 >            BlockingQueue<Runnable> q = p.getQueue();
591 >            assertTrue(q.contains(tasks[tasks.length - 1]));
592 >            assertFalse(q.contains(tasks[0]));
593 >        }
594 >    }
595 >
596 >    /**
597 >     * remove(task) removes queued task, and fails to remove active task
598 >     */
599 >    public void testRemove() throws InterruptedException {
600 >        final CountDownLatch done = new CountDownLatch(1);
601 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
602 >        try (PoolCleaner cleaner = cleaner(p, done)) {
603 >            ScheduledFuture[] tasks = new ScheduledFuture[5];
604 >            final CountDownLatch threadStarted = new CountDownLatch(1);
605 >            for (int i = 0; i < tasks.length; i++) {
606 >                Runnable r = new CheckedRunnable() {
607 >                    public void realRun() throws InterruptedException {
608 >                        threadStarted.countDown();
609 >                        await(done);
610 >                    }};
611 >                tasks[i] = p.schedule(r, 1, MILLISECONDS);
612 >            }
613 >            await(threadStarted);
614 >            BlockingQueue<Runnable> q = p.getQueue();
615 >            assertFalse(p.remove((Runnable)tasks[0]));
616 >            assertTrue(q.contains((Runnable)tasks[4]));
617 >            assertTrue(q.contains((Runnable)tasks[3]));
618 >            assertTrue(p.remove((Runnable)tasks[4]));
619 >            assertFalse(p.remove((Runnable)tasks[4]));
620 >            assertFalse(q.contains((Runnable)tasks[4]));
621 >            assertTrue(q.contains((Runnable)tasks[3]));
622 >            assertTrue(p.remove((Runnable)tasks[3]));
623 >            assertFalse(q.contains((Runnable)tasks[3]));
624 >        }
625      }
626  
627 +    /**
628 +     * purge eventually removes cancelled tasks from the queue
629 +     */
630 +    public void testPurge() throws InterruptedException {
631 +        final ScheduledFuture[] tasks = new ScheduledFuture[5];
632 +        final Runnable releaser = new Runnable() { public void run() {
633 +            for (ScheduledFuture task : tasks)
634 +                if (task != null) task.cancel(true); }};
635 +        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
636 +        try (PoolCleaner cleaner = cleaner(p, releaser)) {
637 +            for (int i = 0; i < tasks.length; i++)
638 +                tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
639 +                                      LONG_DELAY_MS, MILLISECONDS);
640 +            int max = tasks.length;
641 +            if (tasks[4].cancel(true)) --max;
642 +            if (tasks[3].cancel(true)) --max;
643 +            // There must eventually be an interference-free point at
644 +            // which purge will not fail. (At worst, when queue is empty.)
645 +            long startTime = System.nanoTime();
646 +            do {
647 +                p.purge();
648 +                long count = p.getTaskCount();
649 +                if (count == max)
650 +                    return;
651 +            } while (millisElapsedSince(startTime) < LONG_DELAY_MS);
652 +            fail("Purge failed to remove cancelled tasks");
653 +        }
654 +    }
655  
656 +    /**
657 +     * shutdownNow returns a list containing tasks that were not run,
658 +     * and those tasks are drained from the queue
659 +     */
660 +    public void testShutdownNow() throws InterruptedException {
661 +        final int poolSize = 2;
662 +        final int count = 5;
663 +        final AtomicInteger ran = new AtomicInteger(0);
664 +        final ScheduledThreadPoolExecutor p =
665 +            new ScheduledThreadPoolExecutor(poolSize);
666 +        final CountDownLatch threadsStarted = new CountDownLatch(poolSize);
667 +        Runnable waiter = new CheckedRunnable() { public void realRun() {
668 +            threadsStarted.countDown();
669 +            try {
670 +                MILLISECONDS.sleep(2 * LONG_DELAY_MS);
671 +            } catch (InterruptedException success) {}
672 +            ran.getAndIncrement();
673 +        }};
674 +        for (int i = 0; i < count; i++)
675 +            p.execute(waiter);
676 +        await(threadsStarted);
677 +        assertEquals(poolSize, p.getActiveCount());
678 +        assertEquals(0, p.getCompletedTaskCount());
679 +        final List<Runnable> queuedTasks;
680 +        try {
681 +            queuedTasks = p.shutdownNow();
682 +        } catch (SecurityException ok) {
683 +            return; // Allowed in case test doesn't have privs
684 +        }
685 +        assertTrue(p.isShutdown());
686 +        assertTrue(p.getQueue().isEmpty());
687 +        assertEquals(count - poolSize, queuedTasks.size());
688 +        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
689 +        assertTrue(p.isTerminated());
690 +        assertEquals(poolSize, ran.get());
691 +        assertEquals(poolSize, p.getCompletedTaskCount());
692 +    }
693  
694      /**
695 <     *  Test to verify getActiveCount gives correct values
696 <     */
697 <    public void testGetActiveCount(){
698 <        ScheduledExecutor two = new ScheduledExecutor(2);
695 >     * shutdownNow returns a list containing tasks that were not run,
696 >     * and those tasks are drained from the queue
697 >     */
698 >    public void testShutdownNow_delayedTasks() throws InterruptedException {
699 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
700 >        List<ScheduledFuture> tasks = new ArrayList<>();
701 >        for (int i = 0; i < 3; i++) {
702 >            Runnable r = new NoOpRunnable();
703 >            tasks.add(p.schedule(r, 9, SECONDS));
704 >            tasks.add(p.scheduleAtFixedRate(r, 9, 9, SECONDS));
705 >            tasks.add(p.scheduleWithFixedDelay(r, 9, 9, SECONDS));
706 >        }
707 >        if (testImplementationDetails)
708 >            assertEquals(new HashSet(tasks), new HashSet(p.getQueue()));
709 >        final List<Runnable> queuedTasks;
710          try {
711 <            assertEquals(0, two.getActiveCount());
712 <            two.execute(newRunnable());
713 <            try{
714 <                Thread.sleep(SHORT_DELAY_MS/2);
715 <            } catch(Exception e){
716 <                fail("unexpected exception");
711 >            queuedTasks = p.shutdownNow();
712 >        } catch (SecurityException ok) {
713 >            return; // Allowed in case test doesn't have privs
714 >        }
715 >        assertTrue(p.isShutdown());
716 >        assertTrue(p.getQueue().isEmpty());
717 >        if (testImplementationDetails)
718 >            assertEquals(new HashSet(tasks), new HashSet(queuedTasks));
719 >        assertEquals(tasks.size(), queuedTasks.size());
720 >        for (ScheduledFuture task : tasks) {
721 >            assertFalse(task.isDone());
722 >            assertFalse(task.isCancelled());
723 >        }
724 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
725 >        assertTrue(p.isTerminated());
726 >    }
727 >
728 >    /**
729 >     * By default, periodic tasks are cancelled at shutdown.
730 >     * By default, delayed tasks keep running after shutdown.
731 >     * Check that changing the default values work:
732 >     * - setExecuteExistingDelayedTasksAfterShutdownPolicy
733 >     * - setContinueExistingPeriodicTasksAfterShutdownPolicy
734 >     */
735 >    public void testShutdown_cancellation() throws Exception {
736 >        Boolean[] allBooleans = { null, Boolean.FALSE, Boolean.TRUE };
737 >        for (Boolean policy : allBooleans)
738 >    {
739 >        final int poolSize = 2;
740 >        final ScheduledThreadPoolExecutor p
741 >            = new ScheduledThreadPoolExecutor(poolSize);
742 >        final boolean effectiveDelayedPolicy = (policy != Boolean.FALSE);
743 >        final boolean effectivePeriodicPolicy = (policy == Boolean.TRUE);
744 >        final boolean effectiveRemovePolicy = (policy == Boolean.TRUE);
745 >        if (policy != null) {
746 >            p.setExecuteExistingDelayedTasksAfterShutdownPolicy(policy);
747 >            p.setContinueExistingPeriodicTasksAfterShutdownPolicy(policy);
748 >            p.setRemoveOnCancelPolicy(policy);
749 >        }
750 >        assertEquals(effectiveDelayedPolicy,
751 >                     p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
752 >        assertEquals(effectivePeriodicPolicy,
753 >                     p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
754 >        assertEquals(effectiveRemovePolicy,
755 >                     p.getRemoveOnCancelPolicy());
756 >        // Strategy: Wedge the pool with poolSize "blocker" threads
757 >        final AtomicInteger ran = new AtomicInteger(0);
758 >        final CountDownLatch poolBlocked = new CountDownLatch(poolSize);
759 >        final CountDownLatch unblock = new CountDownLatch(1);
760 >        final CountDownLatch periodicLatch1 = new CountDownLatch(2);
761 >        final CountDownLatch periodicLatch2 = new CountDownLatch(2);
762 >        Runnable task = new CheckedRunnable() { public void realRun()
763 >                                                    throws InterruptedException {
764 >            poolBlocked.countDown();
765 >            assertTrue(unblock.await(LONG_DELAY_MS, MILLISECONDS));
766 >            ran.getAndIncrement();
767 >        }};
768 >        List<Future<?>> blockers = new ArrayList<>();
769 >        List<Future<?>> periodics = new ArrayList<>();
770 >        List<Future<?>> delayeds = new ArrayList<>();
771 >        for (int i = 0; i < poolSize; i++)
772 >            blockers.add(p.submit(task));
773 >        assertTrue(poolBlocked.await(LONG_DELAY_MS, MILLISECONDS));
774 >
775 >        periodics.add(p.scheduleAtFixedRate(countDowner(periodicLatch1),
776 >                                            1, 1, MILLISECONDS));
777 >        periodics.add(p.scheduleWithFixedDelay(countDowner(periodicLatch2),
778 >                                               1, 1, MILLISECONDS));
779 >        delayeds.add(p.schedule(task, 1, MILLISECONDS));
780 >
781 >        assertTrue(p.getQueue().containsAll(periodics));
782 >        assertTrue(p.getQueue().containsAll(delayeds));
783 >        try { p.shutdown(); } catch (SecurityException ok) { return; }
784 >        assertTrue(p.isShutdown());
785 >        assertFalse(p.isTerminated());
786 >        for (Future<?> periodic : periodics) {
787 >            assertTrue(effectivePeriodicPolicy ^ periodic.isCancelled());
788 >            assertTrue(effectivePeriodicPolicy ^ periodic.isDone());
789 >        }
790 >        for (Future<?> delayed : delayeds) {
791 >            assertTrue(effectiveDelayedPolicy ^ delayed.isCancelled());
792 >            assertTrue(effectiveDelayedPolicy ^ delayed.isDone());
793 >        }
794 >        if (testImplementationDetails) {
795 >            assertEquals(effectivePeriodicPolicy,
796 >                         p.getQueue().containsAll(periodics));
797 >            assertEquals(effectiveDelayedPolicy,
798 >                         p.getQueue().containsAll(delayeds));
799 >        }
800 >        // Release all pool threads
801 >        unblock.countDown();
802 >
803 >        for (Future<?> delayed : delayeds) {
804 >            if (effectiveDelayedPolicy) {
805 >                assertNull(delayed.get());
806 >            }
807 >        }
808 >        if (effectivePeriodicPolicy) {
809 >            assertTrue(periodicLatch1.await(LONG_DELAY_MS, MILLISECONDS));
810 >            assertTrue(periodicLatch2.await(LONG_DELAY_MS, MILLISECONDS));
811 >            for (Future<?> periodic : periodics) {
812 >                assertTrue(periodic.cancel(false));
813 >                assertTrue(periodic.isCancelled());
814 >                assertTrue(periodic.isDone());
815              }
816 <            assertEquals(1, two.getActiveCount());
817 <        } finally {
818 <            two.shutdown();
816 >        }
817 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
818 >        assertTrue(p.isTerminated());
819 >        assertEquals(2 + (effectiveDelayedPolicy ? 1 : 0), ran.get());
820 >    }}
821 >
822 >    /**
823 >     * completed submit of callable returns result
824 >     */
825 >    public void testSubmitCallable() throws Exception {
826 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
827 >        try (PoolCleaner cleaner = cleaner(e)) {
828 >            Future<String> future = e.submit(new StringTask());
829 >            String result = future.get();
830 >            assertSame(TEST_STRING, result);
831          }
832      }
833 <    
833 >
834      /**
835 <     *  Test to verify getCompleteTaskCount gives correct values
835 >     * completed submit of runnable returns successfully
836       */
837 <    public void testGetCompletedTaskCount(){
838 <        ScheduledExecutor two = new ScheduledExecutor(2);
839 <        try {
840 <            assertEquals(0, two.getCompletedTaskCount());
841 <            two.execute(newRunnable());
842 <            try{
315 <                Thread.sleep(MEDIUM_DELAY_MS);
316 <            } catch(Exception e){
317 <                fail("unexpected exception");
318 <            }
319 <            assertEquals(1, two.getCompletedTaskCount());
320 <        } finally {
321 <            two.shutdown();
837 >    public void testSubmitRunnable() throws Exception {
838 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
839 >        try (PoolCleaner cleaner = cleaner(e)) {
840 >            Future<?> future = e.submit(new NoOpRunnable());
841 >            future.get();
842 >            assertTrue(future.isDone());
843          }
844      }
845 <    
845 >
846      /**
847 <     *  Test to verify getCorePoolSize gives correct values
847 >     * completed submit of (runnable, result) returns result
848       */
849 <    public void testGetCorePoolSize(){
850 <        ScheduledExecutor one = new ScheduledExecutor(1);
851 <        try {
852 <            assertEquals(1, one.getCorePoolSize());
853 <        } finally {
854 <            one.shutdown();
849 >    public void testSubmitRunnable2() throws Exception {
850 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
851 >        try (PoolCleaner cleaner = cleaner(e)) {
852 >            Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
853 >            String result = future.get();
854 >            assertSame(TEST_STRING, result);
855 >        }
856 >    }
857 >
858 >    /**
859 >     * invokeAny(null) throws NPE
860 >     */
861 >    public void testInvokeAny1() throws Exception {
862 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
863 >        try (PoolCleaner cleaner = cleaner(e)) {
864 >            try {
865 >                e.invokeAny(null);
866 >                shouldThrow();
867 >            } catch (NullPointerException success) {}
868          }
869      }
870 <    
870 >
871      /**
872 <     *  Test to verify getLargestPoolSize gives correct values
872 >     * invokeAny(empty collection) throws IAE
873       */
874 <    public void testGetLargestPoolSize(){
875 <        ScheduledExecutor two = new ScheduledExecutor(2);
876 <        try {
877 <            assertEquals(0, two.getLargestPoolSize());
878 <            two.execute(newRunnable());
879 <            two.execute(newRunnable());
880 <            try{
881 <                Thread.sleep(SHORT_DELAY_MS);
882 <            } catch(Exception e){
883 <                fail("unexpected exception");
874 >    public void testInvokeAny2() throws Exception {
875 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
876 >        try (PoolCleaner cleaner = cleaner(e)) {
877 >            try {
878 >                e.invokeAny(new ArrayList<Callable<String>>());
879 >                shouldThrow();
880 >            } catch (IllegalArgumentException success) {}
881 >        }
882 >    }
883 >
884 >    /**
885 >     * invokeAny(c) throws NPE if c has null elements
886 >     */
887 >    public void testInvokeAny3() throws Exception {
888 >        CountDownLatch latch = new CountDownLatch(1);
889 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
890 >        try (PoolCleaner cleaner = cleaner(e)) {
891 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
892 >            l.add(latchAwaitingStringTask(latch));
893 >            l.add(null);
894 >            try {
895 >                e.invokeAny(l);
896 >                shouldThrow();
897 >            } catch (NullPointerException success) {}
898 >            latch.countDown();
899 >        }
900 >    }
901 >
902 >    /**
903 >     * invokeAny(c) throws ExecutionException if no task completes
904 >     */
905 >    public void testInvokeAny4() throws Exception {
906 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
907 >        try (PoolCleaner cleaner = cleaner(e)) {
908 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
909 >            l.add(new NPETask());
910 >            try {
911 >                e.invokeAny(l);
912 >                shouldThrow();
913 >            } catch (ExecutionException success) {
914 >                assertTrue(success.getCause() instanceof NullPointerException);
915              }
351            assertEquals(2, two.getLargestPoolSize());
352        } finally {
353            two.shutdown();
916          }
917      }
918 <    
918 >
919      /**
920 <     *  Test to verify getPoolSize gives correct values
920 >     * invokeAny(c) returns result of some task
921       */
922 <    public void testGetPoolSize(){
923 <        ScheduledExecutor one = new ScheduledExecutor(1);
924 <        try {
925 <            assertEquals(0, one.getPoolSize());
926 <            one.execute(newRunnable());
927 <            assertEquals(1, one.getPoolSize());
928 <        } finally {
929 <            one.shutdown();
922 >    public void testInvokeAny5() throws Exception {
923 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
924 >        try (PoolCleaner cleaner = cleaner(e)) {
925 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
926 >            l.add(new StringTask());
927 >            l.add(new StringTask());
928 >            String result = e.invokeAny(l);
929 >            assertSame(TEST_STRING, result);
930          }
931      }
932 <    
932 >
933      /**
934 <     *  Test to verify getTaskCount gives correct values
934 >     * invokeAll(null) throws NPE
935       */
936 <    public void testGetTaskCount(){
937 <        ScheduledExecutor one = new ScheduledExecutor(1);
938 <        try {
939 <            assertEquals(0, one.getTaskCount());
940 <            for(int i = 0; i < 5; i++)
941 <                one.execute(newRunnable());
942 <            try{
381 <                Thread.sleep(SHORT_DELAY_MS);
382 <            } catch(Exception e){
383 <                fail("unexpected exception");
384 <            }
385 <            assertEquals(5, one.getTaskCount());
386 <        } finally {
387 <            one.shutdown();
388 <        }
389 <    }
390 <    
391 <    /**
392 <     *  Test to verify isShutDown gives correct values
393 <     */
394 <    public void testIsShutdown(){
395 <        
396 <        ScheduledExecutor one = new ScheduledExecutor(1);
397 <        try {
398 <            assertFalse(one.isShutdown());
936 >    public void testInvokeAll1() throws Exception {
937 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
938 >        try (PoolCleaner cleaner = cleaner(e)) {
939 >            try {
940 >                e.invokeAll(null);
941 >                shouldThrow();
942 >            } catch (NullPointerException success) {}
943          }
944 <        finally {
945 <            one.shutdown();
944 >    }
945 >
946 >    /**
947 >     * invokeAll(empty collection) returns empty collection
948 >     */
949 >    public void testInvokeAll2() throws Exception {
950 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
951 >        try (PoolCleaner cleaner = cleaner(e)) {
952 >            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
953 >            assertTrue(r.isEmpty());
954          }
403        assertTrue(one.isShutdown());
955      }
956  
406        
957      /**
958 <     *  Test to verify isTerminated gives correct values
409 <     *  Makes sure termination does not take an innapropriate
410 <     *  amount of time
958 >     * invokeAll(c) throws NPE if c has null elements
959       */
960 <    public void testIsTerminated(){
961 <        ScheduledExecutor one = new ScheduledExecutor(1);
962 <        try {
963 <            one.execute(newRunnable());
964 <        } finally {
965 <            one.shutdown();
966 <        }
967 <        boolean flag = false;
968 <        try{
969 <            flag = one.awaitTermination(10, TimeUnit.SECONDS);
970 <        } catch(Exception e){
423 <            fail("unexpected exception");
424 <        }      
425 <        assertTrue(one.isTerminated());
426 <        if(!flag)
427 <            fail("ThreadPoolExecutor - thread pool did not terminate within suitable timeframe");
960 >    public void testInvokeAll3() throws Exception {
961 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
962 >        try (PoolCleaner cleaner = cleaner(e)) {
963 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
964 >            l.add(new StringTask());
965 >            l.add(null);
966 >            try {
967 >                e.invokeAll(l);
968 >                shouldThrow();
969 >            } catch (NullPointerException success) {}
970 >        }
971      }
972  
973      /**
974 <     *  Test to verify that purge correctly removes cancelled tasks
432 <     *  from the queue
974 >     * get of invokeAll(c) throws exception on failed task
975       */
976 <    public void testPurge(){
977 <        ScheduledExecutor one = new ScheduledExecutor(1);
978 <        try {
979 <            ScheduledCancellable[] tasks = new ScheduledCancellable[5];
980 <            for(int i = 0; i < 5; i++){
981 <                tasks[i] = one.schedule(newRunnable(), 1, TimeUnit.MILLISECONDS);
976 >    public void testInvokeAll4() throws Exception {
977 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
978 >        try (PoolCleaner cleaner = cleaner(e)) {
979 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
980 >            l.add(new NPETask());
981 >            List<Future<String>> futures = e.invokeAll(l);
982 >            assertEquals(1, futures.size());
983 >            try {
984 >                futures.get(0).get();
985 >                shouldThrow();
986 >            } catch (ExecutionException success) {
987 >                assertTrue(success.getCause() instanceof NullPointerException);
988              }
441            int max = 5;
442            if (tasks[4].cancel(true)) --max;
443            if (tasks[3].cancel(true)) --max;
444            one.purge();
445            long count = one.getTaskCount();
446            assertTrue(count > 0 && count <= max);
447        } finally {
448            one.shutdown();
989          }
990      }
991  
992      /**
993 <     *  Test to verify shutDownNow returns a list
454 <     *  containing the correct number of elements
993 >     * invokeAll(c) returns results of all completed tasks
994       */
995 <    public void testShutDownNow(){
996 <        ScheduledExecutor one = new ScheduledExecutor(1);
997 <        for(int i = 0; i < 5; i++)
998 <            one.schedule(newRunnable(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
999 <        List l = one.shutdownNow();
1000 <        assertTrue(one.isShutdown());
1001 <        assertTrue(l.size() > 0 && l.size() <= 5);
995 >    public void testInvokeAll5() throws Exception {
996 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
997 >        try (PoolCleaner cleaner = cleaner(e)) {
998 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
999 >            l.add(new StringTask());
1000 >            l.add(new StringTask());
1001 >            List<Future<String>> futures = e.invokeAll(l);
1002 >            assertEquals(2, futures.size());
1003 >            for (Future<String> future : futures)
1004 >                assertSame(TEST_STRING, future.get());
1005 >        }
1006      }
1007  
1008 <    public void testShutDown1(){
1009 <        try {
1010 <            ScheduledExecutor one = new ScheduledExecutor(1);
1011 <            assertTrue(one.getExecuteExistingDelayedTasksAfterShutdownPolicy());
1012 <            assertFalse(one.getContinueExistingPeriodicTasksAfterShutdownPolicy());
1008 >    /**
1009 >     * timed invokeAny(null) throws NPE
1010 >     */
1011 >    public void testTimedInvokeAny1() throws Exception {
1012 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1013 >        try (PoolCleaner cleaner = cleaner(e)) {
1014 >            try {
1015 >                e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1016 >                shouldThrow();
1017 >            } catch (NullPointerException success) {}
1018 >        }
1019 >    }
1020  
1021 <            ScheduledCancellable[] tasks = new ScheduledCancellable[5];
1022 <            for(int i = 0; i < 5; i++)
1023 <                tasks[i] = one.schedule(newNoopRunnable(), SHORT_DELAY_MS/2, TimeUnit.MILLISECONDS);
1024 <            one.shutdown();
1025 <            BlockingQueue q = one.getQueue();
1026 <            for (Iterator it = q.iterator(); it.hasNext();) {
1027 <                ScheduledCancellable t = (ScheduledCancellable)it.next();
1028 <                assertFalse(t.isCancelled());
1029 <            }
1030 <            assertTrue(one.isShutdown());
1031 <            Thread.sleep(SHORT_DELAY_MS);
1032 <            for (int i = 0; i < 5; ++i) {
483 <                assertTrue(tasks[i].isDone());
484 <                assertFalse(tasks[i].isCancelled());
485 <            }
486 <            
1021 >    /**
1022 >     * timed invokeAny(,,null) throws NPE
1023 >     */
1024 >    public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1025 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1026 >        try (PoolCleaner cleaner = cleaner(e)) {
1027 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
1028 >            l.add(new StringTask());
1029 >            try {
1030 >                e.invokeAny(l, MEDIUM_DELAY_MS, null);
1031 >                shouldThrow();
1032 >            } catch (NullPointerException success) {}
1033          }
1034 <        catch(Exception ex) {
1035 <            fail("unexpected exception");
1034 >    }
1035 >
1036 >    /**
1037 >     * timed invokeAny(empty collection) throws IAE
1038 >     */
1039 >    public void testTimedInvokeAny2() throws Exception {
1040 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1041 >        try (PoolCleaner cleaner = cleaner(e)) {
1042 >            try {
1043 >                e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1044 >                shouldThrow();
1045 >            } catch (IllegalArgumentException success) {}
1046          }
1047      }
1048  
1049 +    /**
1050 +     * timed invokeAny(c) throws NPE if c has null elements
1051 +     */
1052 +    public void testTimedInvokeAny3() throws Exception {
1053 +        CountDownLatch latch = new CountDownLatch(1);
1054 +        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1055 +        try (PoolCleaner cleaner = cleaner(e)) {
1056 +            List<Callable<String>> l = new ArrayList<Callable<String>>();
1057 +            l.add(latchAwaitingStringTask(latch));
1058 +            l.add(null);
1059 +            try {
1060 +                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1061 +                shouldThrow();
1062 +            } catch (NullPointerException success) {}
1063 +            latch.countDown();
1064 +        }
1065 +    }
1066  
1067 <    public void testShutDown2(){
1068 <        try {
1069 <            ScheduledExecutor one = new ScheduledExecutor(1);
1070 <            one.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
1071 <            ScheduledCancellable[] tasks = new ScheduledCancellable[5];
1072 <            for(int i = 0; i < 5; i++)
1073 <                tasks[i] = one.schedule(newNoopRunnable(), SHORT_DELAY_MS/2, TimeUnit.MILLISECONDS);
1074 <            one.shutdown();
1075 <            assertTrue(one.isShutdown());
1076 <            BlockingQueue q = one.getQueue();
1077 <            assertTrue(q.isEmpty());
1078 <            Thread.sleep(SHORT_DELAY_MS);
1079 <            assertTrue(one.isTerminated());
1067 >    /**
1068 >     * timed invokeAny(c) throws ExecutionException if no task completes
1069 >     */
1070 >    public void testTimedInvokeAny4() throws Exception {
1071 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1072 >        try (PoolCleaner cleaner = cleaner(e)) {
1073 >            long startTime = System.nanoTime();
1074 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
1075 >            l.add(new NPETask());
1076 >            try {
1077 >                e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1078 >                shouldThrow();
1079 >            } catch (ExecutionException success) {
1080 >                assertTrue(success.getCause() instanceof NullPointerException);
1081 >            }
1082 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1083          }
1084 <        catch(Exception ex) {
1085 <            fail("unexpected exception");
1084 >    }
1085 >
1086 >    /**
1087 >     * timed invokeAny(c) returns result of some task
1088 >     */
1089 >    public void testTimedInvokeAny5() throws Exception {
1090 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1091 >        try (PoolCleaner cleaner = cleaner(e)) {
1092 >            long startTime = System.nanoTime();
1093 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
1094 >            l.add(new StringTask());
1095 >            l.add(new StringTask());
1096 >            String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1097 >            assertSame(TEST_STRING, result);
1098 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1099          }
1100      }
1101  
1102 +    /**
1103 +     * timed invokeAll(null) throws NPE
1104 +     */
1105 +    public void testTimedInvokeAll1() throws Exception {
1106 +        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1107 +        try (PoolCleaner cleaner = cleaner(e)) {
1108 +            try {
1109 +                e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1110 +                shouldThrow();
1111 +            } catch (NullPointerException success) {}
1112 +        }
1113 +    }
1114  
1115 <    public void testShutDown3(){
1116 <        try {
1117 <            ScheduledExecutor one = new ScheduledExecutor(1);
1118 <            one.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
1119 <            ScheduledCancellable task =
1120 <                one.scheduleAtFixedRate(newNoopRunnable(), 5, 5, TimeUnit.MILLISECONDS);
1121 <            one.shutdown();
1122 <            assertTrue(one.isShutdown());
1123 <            BlockingQueue q = one.getQueue();
1124 <            assertTrue(q.isEmpty());
1125 <            Thread.sleep(SHORT_DELAY_MS);
1126 <            assertTrue(one.isTerminated());
1115 >    /**
1116 >     * timed invokeAll(,,null) throws NPE
1117 >     */
1118 >    public void testTimedInvokeAllNullTimeUnit() throws Exception {
1119 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1120 >        try (PoolCleaner cleaner = cleaner(e)) {
1121 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
1122 >            l.add(new StringTask());
1123 >            try {
1124 >                e.invokeAll(l, MEDIUM_DELAY_MS, null);
1125 >                shouldThrow();
1126 >            } catch (NullPointerException success) {}
1127          }
1128 <        catch(Exception ex) {
1129 <            fail("unexpected exception");
1128 >    }
1129 >
1130 >    /**
1131 >     * timed invokeAll(empty collection) returns empty collection
1132 >     */
1133 >    public void testTimedInvokeAll2() throws Exception {
1134 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1135 >        try (PoolCleaner cleaner = cleaner(e)) {
1136 >            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(),
1137 >                                                 MEDIUM_DELAY_MS, MILLISECONDS);
1138 >            assertTrue(r.isEmpty());
1139          }
1140      }
1141  
1142 <    public void testShutDown4(){
1143 <        ScheduledExecutor one = new ScheduledExecutor(1);
1144 <        try {
1145 <            one.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
1146 <            ScheduledCancellable task =
1147 <                one.scheduleAtFixedRate(newNoopRunnable(), 5, 5, TimeUnit.MILLISECONDS);
1148 <            assertFalse(task.isCancelled());
1149 <            one.shutdown();
1150 <            assertFalse(task.isCancelled());
1151 <            assertFalse(one.isTerminated());
1152 <            assertTrue(one.isShutdown());
1153 <            Thread.sleep(SHORT_DELAY_MS);
1154 <            assertFalse(task.isCancelled());
1155 <            task.cancel(true);
1156 <            assertTrue(task.isCancelled());
1157 <            Thread.sleep(SHORT_DELAY_MS);
1158 <            assertTrue(one.isTerminated());
1142 >    /**
1143 >     * timed invokeAll(c) throws NPE if c has null elements
1144 >     */
1145 >    public void testTimedInvokeAll3() throws Exception {
1146 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1147 >        try (PoolCleaner cleaner = cleaner(e)) {
1148 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
1149 >            l.add(new StringTask());
1150 >            l.add(null);
1151 >            try {
1152 >                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1153 >                shouldThrow();
1154 >            } catch (NullPointerException success) {}
1155 >        }
1156 >    }
1157 >
1158 >    /**
1159 >     * get of element of invokeAll(c) throws exception on failed task
1160 >     */
1161 >    public void testTimedInvokeAll4() throws Exception {
1162 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1163 >        try (PoolCleaner cleaner = cleaner(e)) {
1164 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
1165 >            l.add(new NPETask());
1166 >            List<Future<String>> futures =
1167 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1168 >            assertEquals(1, futures.size());
1169 >            try {
1170 >                futures.get(0).get();
1171 >                shouldThrow();
1172 >            } catch (ExecutionException success) {
1173 >                assertTrue(success.getCause() instanceof NullPointerException);
1174 >            }
1175 >        }
1176 >    }
1177 >
1178 >    /**
1179 >     * timed invokeAll(c) returns results of all completed tasks
1180 >     */
1181 >    public void testTimedInvokeAll5() throws Exception {
1182 >        final ExecutorService e = new ScheduledThreadPoolExecutor(2);
1183 >        try (PoolCleaner cleaner = cleaner(e)) {
1184 >            List<Callable<String>> l = new ArrayList<Callable<String>>();
1185 >            l.add(new StringTask());
1186 >            l.add(new StringTask());
1187 >            List<Future<String>> futures =
1188 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1189 >            assertEquals(2, futures.size());
1190 >            for (Future<String> future : futures)
1191 >                assertSame(TEST_STRING, future.get());
1192          }
1193 <        catch(Exception ex) {
1194 <            fail("unexpected exception");
1193 >    }
1194 >
1195 >    /**
1196 >     * timed invokeAll(c) cancels tasks not completed by timeout
1197 >     */
1198 >    public void testTimedInvokeAll6() throws Exception {
1199 >        for (long timeout = timeoutMillis();;) {
1200 >            final CountDownLatch done = new CountDownLatch(1);
1201 >            final Callable<String> waiter = new CheckedCallable<String>() {
1202 >                public String realCall() {
1203 >                    try { done.await(LONG_DELAY_MS, MILLISECONDS); }
1204 >                    catch (InterruptedException ok) {}
1205 >                    return "1"; }};
1206 >            final ExecutorService p = new ScheduledThreadPoolExecutor(2);
1207 >            try (PoolCleaner cleaner = cleaner(p, done)) {
1208 >                List<Callable<String>> tasks = new ArrayList<>();
1209 >                tasks.add(new StringTask("0"));
1210 >                tasks.add(waiter);
1211 >                tasks.add(new StringTask("2"));
1212 >                long startTime = System.nanoTime();
1213 >                List<Future<String>> futures =
1214 >                    p.invokeAll(tasks, timeout, MILLISECONDS);
1215 >                assertEquals(tasks.size(), futures.size());
1216 >                assertTrue(millisElapsedSince(startTime) >= timeout);
1217 >                for (Future future : futures)
1218 >                    assertTrue(future.isDone());
1219 >                assertTrue(futures.get(1).isCancelled());
1220 >                try {
1221 >                    assertEquals("0", futures.get(0).get());
1222 >                    assertEquals("2", futures.get(2).get());
1223 >                    break;
1224 >                } catch (CancellationException retryWithLongerTimeout) {
1225 >                    timeout *= 2;
1226 >                    if (timeout >= LONG_DELAY_MS / 2)
1227 >                        fail("expected exactly one task to be cancelled");
1228 >                }
1229 >            }
1230          }
1231 <        finally {
1232 <            one.shutdownNow();
1231 >    }
1232 >
1233 >    /**
1234 >     * A fixed delay task with overflowing period should not prevent a
1235 >     * one-shot task from executing.
1236 >     * https://bugs.openjdk.java.net/browse/JDK-8051859
1237 >     */
1238 >    public void testScheduleWithFixedDelay_overflow() throws Exception {
1239 >        final CountDownLatch delayedDone = new CountDownLatch(1);
1240 >        final CountDownLatch immediateDone = new CountDownLatch(1);
1241 >        final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
1242 >        try (PoolCleaner cleaner = cleaner(p)) {
1243 >            final Runnable immediate = new Runnable() { public void run() {
1244 >                immediateDone.countDown();
1245 >            }};
1246 >            final Runnable delayed = new Runnable() { public void run() {
1247 >                delayedDone.countDown();
1248 >                p.submit(immediate);
1249 >            }};
1250 >            p.scheduleWithFixedDelay(delayed, 0L, Long.MAX_VALUE, SECONDS);
1251 >            await(delayedDone);
1252 >            await(immediateDone);
1253          }
1254      }
1255  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines