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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines