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.49 by jsr166, Wed Sep 25 07:39:17 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines