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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines