ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ScheduledExecutorTest.java
Revision: 1.100
Committed: Wed Jan 27 01:57:24 2021 UTC (3 years, 3 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.99: +2 -2 lines
Log Message:
use diamond <> pervasively

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