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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines