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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines