ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ScheduledExecutorTest.java
Revision: 1.87
Committed: Sat Mar 25 23:35:15 2017 UTC (7 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.86: +25 -20 lines
Log Message:
testShutdown_cancellation: minor improvements

File Contents

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