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.53 by jsr166, Sun Sep 27 18:50:50 2015 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines