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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines