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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines