ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ScheduledExecutorTest.java
Revision: 1.88
Committed: Sun Mar 26 02:00:39 2017 UTC (7 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.87: +25 -12 lines
Log Message:
testShutdown_cancellation: randomize policies

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