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

File Contents

# User Rev Content
1 dl 1.1 /*
2 dl 1.15 * 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.40 * http://creativecommons.org/publicdomain/zero/1.0/
5 jsr166 1.24 * Other contributors include Andrew Wright, Jeffrey Hayes,
6     * Pat Fisher, Mike Judd.
7 dl 1.1 */
8    
9 jsr166 1.27 import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 jsr166 1.48 import static java.util.concurrent.TimeUnit.NANOSECONDS;
11 jsr166 1.52 import static java.util.concurrent.TimeUnit.SECONDS;
12 jsr166 1.50
13     import java.util.ArrayList;
14 jsr166 1.119 import java.util.Collection;
15     import java.util.Collections;
16 jsr166 1.50 import java.util.List;
17     import java.util.concurrent.ArrayBlockingQueue;
18     import java.util.concurrent.BlockingQueue;
19 jsr166 1.58 import java.util.concurrent.Callable;
20 jsr166 1.56 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.FutureTask;
26     import java.util.concurrent.LinkedBlockingQueue;
27     import java.util.concurrent.RejectedExecutionException;
28     import java.util.concurrent.RejectedExecutionHandler;
29     import java.util.concurrent.SynchronousQueue;
30     import java.util.concurrent.ThreadFactory;
31 jsr166 1.123 import java.util.concurrent.ThreadLocalRandom;
32 jsr166 1.50 import java.util.concurrent.ThreadPoolExecutor;
33 jsr166 1.121 import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
34     import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
35     import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy;
36     import java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy;
37 jsr166 1.61 import java.util.concurrent.atomic.AtomicInteger;
38 jsr166 1.121 import java.util.concurrent.atomic.AtomicReference;
39 jsr166 1.50
40     import junit.framework.Test;
41     import junit.framework.TestSuite;
42 dl 1.1
43 dl 1.3 public class ThreadPoolExecutorTest extends JSR166TestCase {
44 dl 1.1 public static void main(String[] args) {
45 jsr166 1.51 main(suite(), args);
46 dl 1.1 }
47     public static Test suite() {
48     return new TestSuite(ThreadPoolExecutorTest.class);
49     }
50 jsr166 1.24
51 dl 1.8 static class ExtendedTPE extends ThreadPoolExecutor {
52 jsr166 1.45 final CountDownLatch beforeCalled = new CountDownLatch(1);
53     final CountDownLatch afterCalled = new CountDownLatch(1);
54     final CountDownLatch terminatedCalled = new CountDownLatch(1);
55    
56 dl 1.8 public ExtendedTPE() {
57 jsr166 1.27 super(1, 1, LONG_DELAY_MS, MILLISECONDS, new SynchronousQueue<Runnable>());
58 dl 1.8 }
59     protected void beforeExecute(Thread t, Runnable r) {
60 jsr166 1.45 beforeCalled.countDown();
61 dl 1.8 }
62     protected void afterExecute(Runnable r, Throwable t) {
63 jsr166 1.45 afterCalled.countDown();
64 dl 1.8 }
65     protected void terminated() {
66 jsr166 1.45 terminatedCalled.countDown();
67     }
68    
69     public boolean beforeCalled() {
70     return beforeCalled.getCount() == 0;
71     }
72     public boolean afterCalled() {
73     return afterCalled.getCount() == 0;
74     }
75     public boolean terminatedCalled() {
76     return terminatedCalled.getCount() == 0;
77 dl 1.8 }
78     }
79 dl 1.1
80 jsr166 1.26 static class FailingThreadFactory implements ThreadFactory {
81 dl 1.19 int calls = 0;
82 jsr166 1.26 public Thread newThread(Runnable r) {
83 dl 1.20 if (++calls > 1) return null;
84 dl 1.19 return new Thread(r);
85 jsr166 1.24 }
86 dl 1.19 }
87 jsr166 1.24
88 dl 1.3 /**
89 jsr166 1.35 * execute successfully executes a runnable
90 dl 1.1 */
91 jsr166 1.27 public void testExecute() throws InterruptedException {
92 jsr166 1.37 final ThreadPoolExecutor p =
93     new ThreadPoolExecutor(1, 1,
94     LONG_DELAY_MS, MILLISECONDS,
95     new ArrayBlockingQueue<Runnable>(10));
96 jsr166 1.80 try (PoolCleaner cleaner = cleaner(p)) {
97     final CountDownLatch done = new CountDownLatch(1);
98     final Runnable task = new CheckedRunnable() {
99     public void realRun() { done.countDown(); }};
100 jsr166 1.37 p.execute(task);
101 jsr166 1.117 await(done);
102 jsr166 1.24 }
103 dl 1.1 }
104    
105     /**
106 jsr166 1.35 * getActiveCount increases but doesn't overestimate, when a
107     * thread becomes active
108 dl 1.1 */
109 jsr166 1.27 public void testGetActiveCount() throws InterruptedException {
110 jsr166 1.109 final CountDownLatch done = new CountDownLatch(1);
111 jsr166 1.37 final ThreadPoolExecutor p =
112     new ThreadPoolExecutor(2, 2,
113     LONG_DELAY_MS, MILLISECONDS,
114     new ArrayBlockingQueue<Runnable>(10));
115 jsr166 1.109 try (PoolCleaner cleaner = cleaner(p, done)) {
116 jsr166 1.80 final CountDownLatch threadStarted = new CountDownLatch(1);
117 jsr166 1.37 assertEquals(0, p.getActiveCount());
118     p.execute(new CheckedRunnable() {
119     public void realRun() throws InterruptedException {
120     threadStarted.countDown();
121     assertEquals(1, p.getActiveCount());
122 jsr166 1.106 await(done);
123 jsr166 1.37 }});
124 jsr166 1.108 await(threadStarted);
125 jsr166 1.37 assertEquals(1, p.getActiveCount());
126     }
127 dl 1.1 }
128 dl 1.8
129     /**
130 jsr166 1.35 * prestartCoreThread starts a thread if under corePoolSize, else doesn't
131 dl 1.8 */
132     public void testPrestartCoreThread() {
133 jsr166 1.37 final ThreadPoolExecutor p =
134 jsr166 1.66 new ThreadPoolExecutor(2, 6,
135 jsr166 1.37 LONG_DELAY_MS, MILLISECONDS,
136     new ArrayBlockingQueue<Runnable>(10));
137 jsr166 1.66 try (PoolCleaner cleaner = cleaner(p)) {
138     assertEquals(0, p.getPoolSize());
139     assertTrue(p.prestartCoreThread());
140     assertEquals(1, p.getPoolSize());
141     assertTrue(p.prestartCoreThread());
142     assertEquals(2, p.getPoolSize());
143     assertFalse(p.prestartCoreThread());
144     assertEquals(2, p.getPoolSize());
145     p.setCorePoolSize(4);
146     assertTrue(p.prestartCoreThread());
147     assertEquals(3, p.getPoolSize());
148     assertTrue(p.prestartCoreThread());
149     assertEquals(4, p.getPoolSize());
150     assertFalse(p.prestartCoreThread());
151     assertEquals(4, p.getPoolSize());
152     }
153 dl 1.8 }
154    
155     /**
156 jsr166 1.35 * prestartAllCoreThreads starts all corePoolSize threads
157 dl 1.8 */
158     public void testPrestartAllCoreThreads() {
159 jsr166 1.37 final ThreadPoolExecutor p =
160 jsr166 1.67 new ThreadPoolExecutor(2, 6,
161 jsr166 1.37 LONG_DELAY_MS, MILLISECONDS,
162     new ArrayBlockingQueue<Runnable>(10));
163 jsr166 1.67 try (PoolCleaner cleaner = cleaner(p)) {
164     assertEquals(0, p.getPoolSize());
165     p.prestartAllCoreThreads();
166     assertEquals(2, p.getPoolSize());
167     p.prestartAllCoreThreads();
168     assertEquals(2, p.getPoolSize());
169     p.setCorePoolSize(4);
170     p.prestartAllCoreThreads();
171     assertEquals(4, p.getPoolSize());
172     p.prestartAllCoreThreads();
173     assertEquals(4, p.getPoolSize());
174     }
175 dl 1.8 }
176 jsr166 1.24
177 dl 1.1 /**
178 jsr166 1.35 * getCompletedTaskCount increases, but doesn't overestimate,
179     * when tasks complete
180 dl 1.1 */
181 jsr166 1.27 public void testGetCompletedTaskCount() throws InterruptedException {
182 jsr166 1.37 final ThreadPoolExecutor p =
183     new ThreadPoolExecutor(2, 2,
184     LONG_DELAY_MS, MILLISECONDS,
185     new ArrayBlockingQueue<Runnable>(10));
186 jsr166 1.68 try (PoolCleaner cleaner = cleaner(p)) {
187     final CountDownLatch threadStarted = new CountDownLatch(1);
188     final CountDownLatch threadProceed = new CountDownLatch(1);
189     final CountDownLatch threadDone = new CountDownLatch(1);
190 jsr166 1.37 assertEquals(0, p.getCompletedTaskCount());
191     p.execute(new CheckedRunnable() {
192     public void realRun() throws InterruptedException {
193     threadStarted.countDown();
194     assertEquals(0, p.getCompletedTaskCount());
195 jsr166 1.117 await(threadProceed);
196 jsr166 1.37 threadDone.countDown();
197     }});
198 jsr166 1.45 await(threadStarted);
199 jsr166 1.37 assertEquals(0, p.getCompletedTaskCount());
200     threadProceed.countDown();
201 jsr166 1.117 await(threadDone);
202 jsr166 1.45 long startTime = System.nanoTime();
203     while (p.getCompletedTaskCount() != 1) {
204     if (millisElapsedSince(startTime) > LONG_DELAY_MS)
205     fail("timed out");
206     Thread.yield();
207     }
208 jsr166 1.37 }
209 dl 1.1 }
210 jsr166 1.24
211 dl 1.1 /**
212 jsr166 1.35 * getCorePoolSize returns size given in constructor if not otherwise set
213 dl 1.1 */
214 dl 1.5 public void testGetCorePoolSize() {
215 jsr166 1.37 final ThreadPoolExecutor p =
216     new ThreadPoolExecutor(1, 1,
217     LONG_DELAY_MS, MILLISECONDS,
218     new ArrayBlockingQueue<Runnable>(10));
219 jsr166 1.69 try (PoolCleaner cleaner = cleaner(p)) {
220     assertEquals(1, p.getCorePoolSize());
221     }
222 dl 1.1 }
223 jsr166 1.24
224 dl 1.1 /**
225 jsr166 1.35 * getKeepAliveTime returns value given in constructor if not otherwise set
226 dl 1.1 */
227 dl 1.5 public void testGetKeepAliveTime() {
228 jsr166 1.37 final ThreadPoolExecutor p =
229     new ThreadPoolExecutor(2, 2,
230     1000, MILLISECONDS,
231     new ArrayBlockingQueue<Runnable>(10));
232 jsr166 1.70 try (PoolCleaner cleaner = cleaner(p)) {
233     assertEquals(1, p.getKeepAliveTime(SECONDS));
234     }
235 dl 1.1 }
236 dl 1.8
237 jsr166 1.24 /**
238 dl 1.8 * getThreadFactory returns factory in constructor if not set
239     */
240     public void testGetThreadFactory() {
241 jsr166 1.71 ThreadFactory threadFactory = new SimpleThreadFactory();
242 jsr166 1.37 final ThreadPoolExecutor p =
243     new ThreadPoolExecutor(1, 2,
244     LONG_DELAY_MS, MILLISECONDS,
245     new ArrayBlockingQueue<Runnable>(10),
246 jsr166 1.71 threadFactory,
247 jsr166 1.37 new NoOpREHandler());
248 jsr166 1.71 try (PoolCleaner cleaner = cleaner(p)) {
249     assertSame(threadFactory, p.getThreadFactory());
250     }
251 dl 1.8 }
252    
253 jsr166 1.24 /**
254 dl 1.8 * setThreadFactory sets the thread factory returned by getThreadFactory
255     */
256     public void testSetThreadFactory() {
257 jsr166 1.37 final ThreadPoolExecutor p =
258     new ThreadPoolExecutor(1, 2,
259     LONG_DELAY_MS, MILLISECONDS,
260     new ArrayBlockingQueue<Runnable>(10));
261 jsr166 1.71 try (PoolCleaner cleaner = cleaner(p)) {
262     ThreadFactory threadFactory = new SimpleThreadFactory();
263     p.setThreadFactory(threadFactory);
264     assertSame(threadFactory, p.getThreadFactory());
265     }
266 dl 1.8 }
267    
268 jsr166 1.24 /**
269 dl 1.8 * setThreadFactory(null) throws NPE
270     */
271     public void testSetThreadFactoryNull() {
272 jsr166 1.37 final ThreadPoolExecutor p =
273     new ThreadPoolExecutor(1, 2,
274     LONG_DELAY_MS, MILLISECONDS,
275     new ArrayBlockingQueue<Runnable>(10));
276 jsr166 1.72 try (PoolCleaner cleaner = cleaner(p)) {
277     try {
278     p.setThreadFactory(null);
279     shouldThrow();
280     } catch (NullPointerException success) {}
281 dl 1.8 }
282     }
283    
284 jsr166 1.24 /**
285 jsr166 1.116 * The default rejected execution handler is AbortPolicy.
286     */
287     public void testDefaultRejectedExecutionHandler() {
288     final ThreadPoolExecutor p =
289     new ThreadPoolExecutor(1, 2,
290     LONG_DELAY_MS, MILLISECONDS,
291     new ArrayBlockingQueue<Runnable>(10));
292     try (PoolCleaner cleaner = cleaner(p)) {
293 jsr166 1.121 assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy);
294 jsr166 1.116 }
295     }
296    
297     /**
298 dl 1.9 * getRejectedExecutionHandler returns handler in constructor if not set
299     */
300     public void testGetRejectedExecutionHandler() {
301 jsr166 1.73 final RejectedExecutionHandler handler = new NoOpREHandler();
302 jsr166 1.37 final ThreadPoolExecutor p =
303     new ThreadPoolExecutor(1, 2,
304     LONG_DELAY_MS, MILLISECONDS,
305     new ArrayBlockingQueue<Runnable>(10),
306 jsr166 1.73 handler);
307     try (PoolCleaner cleaner = cleaner(p)) {
308     assertSame(handler, p.getRejectedExecutionHandler());
309     }
310 dl 1.9 }
311    
312 jsr166 1.24 /**
313 dl 1.9 * setRejectedExecutionHandler sets the handler returned by
314     * getRejectedExecutionHandler
315     */
316     public void testSetRejectedExecutionHandler() {
317 jsr166 1.37 final ThreadPoolExecutor p =
318     new ThreadPoolExecutor(1, 2,
319     LONG_DELAY_MS, MILLISECONDS,
320     new ArrayBlockingQueue<Runnable>(10));
321 jsr166 1.74 try (PoolCleaner cleaner = cleaner(p)) {
322     RejectedExecutionHandler handler = new NoOpREHandler();
323     p.setRejectedExecutionHandler(handler);
324     assertSame(handler, p.getRejectedExecutionHandler());
325     }
326 dl 1.9 }
327    
328 jsr166 1.24 /**
329 dl 1.9 * setRejectedExecutionHandler(null) throws NPE
330     */
331     public void testSetRejectedExecutionHandlerNull() {
332 jsr166 1.37 final ThreadPoolExecutor p =
333     new ThreadPoolExecutor(1, 2,
334     LONG_DELAY_MS, MILLISECONDS,
335     new ArrayBlockingQueue<Runnable>(10));
336 jsr166 1.75 try (PoolCleaner cleaner = cleaner(p)) {
337     try {
338     p.setRejectedExecutionHandler(null);
339     shouldThrow();
340     } catch (NullPointerException success) {}
341 dl 1.9 }
342     }
343    
344 dl 1.1 /**
345 jsr166 1.35 * getLargestPoolSize increases, but doesn't overestimate, when
346     * multiple threads active
347 dl 1.1 */
348 jsr166 1.27 public void testGetLargestPoolSize() throws InterruptedException {
349 jsr166 1.37 final int THREADS = 3;
350 jsr166 1.103 final CountDownLatch done = new CountDownLatch(1);
351 jsr166 1.37 final ThreadPoolExecutor p =
352     new ThreadPoolExecutor(THREADS, THREADS,
353     LONG_DELAY_MS, MILLISECONDS,
354     new ArrayBlockingQueue<Runnable>(10));
355 jsr166 1.103 try (PoolCleaner cleaner = cleaner(p, done)) {
356     assertEquals(0, p.getLargestPoolSize());
357 jsr166 1.76 final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
358 jsr166 1.37 for (int i = 0; i < THREADS; i++)
359     p.execute(new CheckedRunnable() {
360     public void realRun() throws InterruptedException {
361     threadsStarted.countDown();
362 jsr166 1.106 await(done);
363 jsr166 1.37 assertEquals(THREADS, p.getLargestPoolSize());
364     }});
365 jsr166 1.107 await(threadsStarted);
366 jsr166 1.37 assertEquals(THREADS, p.getLargestPoolSize());
367     }
368 jsr166 1.76 assertEquals(THREADS, p.getLargestPoolSize());
369 dl 1.1 }
370 jsr166 1.24
371 dl 1.1 /**
372 jsr166 1.35 * getMaximumPoolSize returns value given in constructor if not
373     * otherwise set
374 dl 1.1 */
375 dl 1.5 public void testGetMaximumPoolSize() {
376 jsr166 1.37 final ThreadPoolExecutor p =
377     new ThreadPoolExecutor(2, 3,
378     LONG_DELAY_MS, MILLISECONDS,
379     new ArrayBlockingQueue<Runnable>(10));
380 jsr166 1.77 try (PoolCleaner cleaner = cleaner(p)) {
381     assertEquals(3, p.getMaximumPoolSize());
382     p.setMaximumPoolSize(5);
383     assertEquals(5, p.getMaximumPoolSize());
384     p.setMaximumPoolSize(4);
385     assertEquals(4, p.getMaximumPoolSize());
386     }
387 dl 1.1 }
388 jsr166 1.24
389 dl 1.1 /**
390 jsr166 1.35 * getPoolSize increases, but doesn't overestimate, when threads
391     * become active
392 dl 1.1 */
393 jsr166 1.37 public void testGetPoolSize() throws InterruptedException {
394 jsr166 1.103 final CountDownLatch done = new CountDownLatch(1);
395 jsr166 1.37 final ThreadPoolExecutor p =
396     new ThreadPoolExecutor(1, 1,
397     LONG_DELAY_MS, MILLISECONDS,
398     new ArrayBlockingQueue<Runnable>(10));
399 jsr166 1.103 try (PoolCleaner cleaner = cleaner(p, done)) {
400     assertEquals(0, p.getPoolSize());
401 jsr166 1.78 final CountDownLatch threadStarted = new CountDownLatch(1);
402 jsr166 1.37 p.execute(new CheckedRunnable() {
403     public void realRun() throws InterruptedException {
404     threadStarted.countDown();
405     assertEquals(1, p.getPoolSize());
406 jsr166 1.106 await(done);
407 jsr166 1.37 }});
408 jsr166 1.108 await(threadStarted);
409 jsr166 1.37 assertEquals(1, p.getPoolSize());
410     }
411 dl 1.1 }
412 jsr166 1.24
413 dl 1.1 /**
414 jsr166 1.35 * getTaskCount increases, but doesn't overestimate, when tasks submitted
415 dl 1.1 */
416 jsr166 1.27 public void testGetTaskCount() throws InterruptedException {
417 jsr166 1.100 final int TASKS = 3;
418     final CountDownLatch done = new CountDownLatch(1);
419 jsr166 1.37 final ThreadPoolExecutor p =
420     new ThreadPoolExecutor(1, 1,
421     LONG_DELAY_MS, MILLISECONDS,
422     new ArrayBlockingQueue<Runnable>(10));
423 jsr166 1.100 try (PoolCleaner cleaner = cleaner(p, done)) {
424 jsr166 1.81 final CountDownLatch threadStarted = new CountDownLatch(1);
425 jsr166 1.37 assertEquals(0, p.getTaskCount());
426 jsr166 1.100 assertEquals(0, p.getCompletedTaskCount());
427 jsr166 1.37 p.execute(new CheckedRunnable() {
428     public void realRun() throws InterruptedException {
429     threadStarted.countDown();
430 jsr166 1.106 await(done);
431 jsr166 1.37 }});
432 jsr166 1.108 await(threadStarted);
433 jsr166 1.37 assertEquals(1, p.getTaskCount());
434 jsr166 1.100 assertEquals(0, p.getCompletedTaskCount());
435     for (int i = 0; i < TASKS; i++) {
436     assertEquals(1 + i, p.getTaskCount());
437     p.execute(new CheckedRunnable() {
438     public void realRun() throws InterruptedException {
439     threadStarted.countDown();
440     assertEquals(1 + TASKS, p.getTaskCount());
441 jsr166 1.106 await(done);
442 jsr166 1.100 }});
443     }
444     assertEquals(1 + TASKS, p.getTaskCount());
445     assertEquals(0, p.getCompletedTaskCount());
446 jsr166 1.37 }
447 jsr166 1.100 assertEquals(1 + TASKS, p.getTaskCount());
448     assertEquals(1 + TASKS, p.getCompletedTaskCount());
449 dl 1.1 }
450 jsr166 1.24
451 dl 1.1 /**
452 jsr166 1.43 * isShutdown is false before shutdown, true after
453 dl 1.1 */
454 dl 1.5 public void testIsShutdown() {
455 jsr166 1.37 final ThreadPoolExecutor p =
456     new ThreadPoolExecutor(1, 1,
457     LONG_DELAY_MS, MILLISECONDS,
458     new ArrayBlockingQueue<Runnable>(10));
459 jsr166 1.82 try (PoolCleaner cleaner = cleaner(p)) {
460     assertFalse(p.isShutdown());
461     try { p.shutdown(); } catch (SecurityException ok) { return; }
462     assertTrue(p.isShutdown());
463     }
464 dl 1.1 }
465    
466     /**
467 jsr166 1.48 * awaitTermination on a non-shutdown pool times out
468     */
469     public void testAwaitTermination_timesOut() throws InterruptedException {
470     final ThreadPoolExecutor p =
471     new ThreadPoolExecutor(1, 1,
472     LONG_DELAY_MS, MILLISECONDS,
473     new ArrayBlockingQueue<Runnable>(10));
474 jsr166 1.84 try (PoolCleaner cleaner = cleaner(p)) {
475     assertFalse(p.isTerminated());
476     assertFalse(p.awaitTermination(Long.MIN_VALUE, NANOSECONDS));
477     assertFalse(p.awaitTermination(Long.MIN_VALUE, MILLISECONDS));
478     assertFalse(p.awaitTermination(-1L, NANOSECONDS));
479     assertFalse(p.awaitTermination(-1L, MILLISECONDS));
480 jsr166 1.118 assertFalse(p.awaitTermination(randomExpiredTimeout(),
481     randomTimeUnit()));
482 jsr166 1.84 long timeoutNanos = 999999L;
483     long startTime = System.nanoTime();
484     assertFalse(p.awaitTermination(timeoutNanos, NANOSECONDS));
485     assertTrue(System.nanoTime() - startTime >= timeoutNanos);
486     assertFalse(p.isTerminated());
487     startTime = System.nanoTime();
488     long timeoutMillis = timeoutMillis();
489     assertFalse(p.awaitTermination(timeoutMillis, MILLISECONDS));
490     assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
491     assertFalse(p.isTerminated());
492     try { p.shutdown(); } catch (SecurityException ok) { return; }
493     assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
494     assertTrue(p.isTerminated());
495     }
496 jsr166 1.48 }
497    
498     /**
499 jsr166 1.35 * isTerminated is false before termination, true after
500 dl 1.1 */
501 jsr166 1.27 public void testIsTerminated() throws InterruptedException {
502 jsr166 1.37 final ThreadPoolExecutor p =
503     new ThreadPoolExecutor(1, 1,
504     LONG_DELAY_MS, MILLISECONDS,
505     new ArrayBlockingQueue<Runnable>(10));
506 jsr166 1.83 try (PoolCleaner cleaner = cleaner(p)) {
507     final CountDownLatch threadStarted = new CountDownLatch(1);
508     final CountDownLatch done = new CountDownLatch(1);
509     assertFalse(p.isTerminating());
510 jsr166 1.37 p.execute(new CheckedRunnable() {
511     public void realRun() throws InterruptedException {
512 jsr166 1.83 assertFalse(p.isTerminating());
513 jsr166 1.37 threadStarted.countDown();
514 jsr166 1.106 await(done);
515 jsr166 1.37 }});
516 jsr166 1.108 await(threadStarted);
517 jsr166 1.39 assertFalse(p.isTerminating());
518 jsr166 1.37 done.countDown();
519     try { p.shutdown(); } catch (SecurityException ok) { return; }
520 jsr166 1.83 assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
521     assertTrue(p.isTerminated());
522     assertFalse(p.isTerminating());
523 dl 1.1 }
524 dl 1.5 }
525    
526     /**
527 jsr166 1.35 * isTerminating is not true when running or when terminated
528 dl 1.5 */
529 jsr166 1.27 public void testIsTerminating() throws InterruptedException {
530 jsr166 1.37 final ThreadPoolExecutor p =
531     new ThreadPoolExecutor(1, 1,
532     LONG_DELAY_MS, MILLISECONDS,
533     new ArrayBlockingQueue<Runnable>(10));
534 jsr166 1.85 try (PoolCleaner cleaner = cleaner(p)) {
535     final CountDownLatch threadStarted = new CountDownLatch(1);
536     final CountDownLatch done = new CountDownLatch(1);
537 jsr166 1.37 assertFalse(p.isTerminating());
538     p.execute(new CheckedRunnable() {
539     public void realRun() throws InterruptedException {
540 jsr166 1.38 assertFalse(p.isTerminating());
541 jsr166 1.37 threadStarted.countDown();
542 jsr166 1.106 await(done);
543 jsr166 1.37 }});
544 jsr166 1.108 await(threadStarted);
545 jsr166 1.37 assertFalse(p.isTerminating());
546     done.countDown();
547     try { p.shutdown(); } catch (SecurityException ok) { return; }
548 jsr166 1.85 assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
549     assertTrue(p.isTerminated());
550     assertFalse(p.isTerminating());
551 jsr166 1.37 }
552 dl 1.1 }
553    
554     /**
555 dl 1.8 * getQueue returns the work queue, which contains queued tasks
556     */
557 jsr166 1.27 public void testGetQueue() throws InterruptedException {
558 jsr166 1.109 final CountDownLatch done = new CountDownLatch(1);
559 jsr166 1.114 final BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(10);
560 jsr166 1.37 final ThreadPoolExecutor p =
561     new ThreadPoolExecutor(1, 1,
562     LONG_DELAY_MS, MILLISECONDS,
563     q);
564 jsr166 1.109 try (PoolCleaner cleaner = cleaner(p, done)) {
565 jsr166 1.86 final CountDownLatch threadStarted = new CountDownLatch(1);
566 dl 1.127 FutureTask[] rtasks = new FutureTask[5];
567     @SuppressWarnings("unchecked")
568     FutureTask<Boolean>[] tasks = (FutureTask<Boolean>[])rtasks;
569 jsr166 1.37 for (int i = 0; i < tasks.length; i++) {
570 jsr166 1.128 Callable<Boolean> task = new CheckedCallable<>() {
571 jsr166 1.37 public Boolean realCall() throws InterruptedException {
572     threadStarted.countDown();
573     assertSame(q, p.getQueue());
574 jsr166 1.106 await(done);
575 jsr166 1.37 return Boolean.TRUE;
576     }};
577 jsr166 1.128 tasks[i] = new FutureTask<>(task);
578 jsr166 1.37 p.execute(tasks[i]);
579     }
580 jsr166 1.108 await(threadStarted);
581 jsr166 1.37 assertSame(q, p.getQueue());
582     assertFalse(q.contains(tasks[0]));
583     assertTrue(q.contains(tasks[tasks.length - 1]));
584     assertEquals(tasks.length - 1, q.size());
585 dl 1.8 }
586     }
587    
588     /**
589     * remove(task) removes queued task, and fails to remove active task
590     */
591 jsr166 1.27 public void testRemove() throws InterruptedException {
592 jsr166 1.109 final CountDownLatch done = new CountDownLatch(1);
593 jsr166 1.114 BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(10);
594 jsr166 1.37 final ThreadPoolExecutor p =
595     new ThreadPoolExecutor(1, 1,
596     LONG_DELAY_MS, MILLISECONDS,
597     q);
598 jsr166 1.109 try (PoolCleaner cleaner = cleaner(p, done)) {
599 jsr166 1.87 Runnable[] tasks = new Runnable[6];
600     final CountDownLatch threadStarted = new CountDownLatch(1);
601 jsr166 1.37 for (int i = 0; i < tasks.length; i++) {
602     tasks[i] = new CheckedRunnable() {
603     public void realRun() throws InterruptedException {
604     threadStarted.countDown();
605 jsr166 1.106 await(done);
606 jsr166 1.37 }};
607     p.execute(tasks[i]);
608     }
609 jsr166 1.108 await(threadStarted);
610 jsr166 1.37 assertFalse(p.remove(tasks[0]));
611 dl 1.8 assertTrue(q.contains(tasks[4]));
612     assertTrue(q.contains(tasks[3]));
613 jsr166 1.37 assertTrue(p.remove(tasks[4]));
614     assertFalse(p.remove(tasks[4]));
615 dl 1.8 assertFalse(q.contains(tasks[4]));
616     assertTrue(q.contains(tasks[3]));
617 jsr166 1.37 assertTrue(p.remove(tasks[3]));
618 dl 1.8 assertFalse(q.contains(tasks[3]));
619     }
620     }
621    
622     /**
623 jsr166 1.35 * purge removes cancelled tasks from the queue
624 dl 1.1 */
625 jsr166 1.37 public void testPurge() throws InterruptedException {
626     final CountDownLatch threadStarted = new CountDownLatch(1);
627     final CountDownLatch done = new CountDownLatch(1);
628 jsr166 1.114 final BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(10);
629 jsr166 1.37 final ThreadPoolExecutor p =
630     new ThreadPoolExecutor(1, 1,
631     LONG_DELAY_MS, MILLISECONDS,
632     q);
633 jsr166 1.101 try (PoolCleaner cleaner = cleaner(p, done)) {
634 dl 1.127 FutureTask[] rtasks = new FutureTask[5];
635     @SuppressWarnings("unchecked")
636     FutureTask<Boolean>[] tasks = (FutureTask<Boolean>[])rtasks;
637 jsr166 1.37 for (int i = 0; i < tasks.length; i++) {
638 jsr166 1.128 Callable<Boolean> task = new CheckedCallable<>() {
639 jsr166 1.37 public Boolean realCall() throws InterruptedException {
640     threadStarted.countDown();
641 jsr166 1.106 await(done);
642 jsr166 1.37 return Boolean.TRUE;
643     }};
644 jsr166 1.128 tasks[i] = new FutureTask<>(task);
645 jsr166 1.37 p.execute(tasks[i]);
646     }
647 jsr166 1.108 await(threadStarted);
648 jsr166 1.37 assertEquals(tasks.length, p.getTaskCount());
649     assertEquals(tasks.length - 1, q.size());
650     assertEquals(1L, p.getActiveCount());
651     assertEquals(0L, p.getCompletedTaskCount());
652     tasks[4].cancel(true);
653     tasks[3].cancel(false);
654     p.purge();
655     assertEquals(tasks.length - 3, q.size());
656     assertEquals(tasks.length - 2, p.getTaskCount());
657     p.purge(); // Nothing to do
658     assertEquals(tasks.length - 3, q.size());
659     assertEquals(tasks.length - 2, p.getTaskCount());
660     }
661 dl 1.1 }
662    
663     /**
664 jsr166 1.60 * shutdownNow returns a list containing tasks that were not run,
665     * and those tasks are drained from the queue
666 dl 1.1 */
667 jsr166 1.61 public void testShutdownNow() throws InterruptedException {
668     final int poolSize = 2;
669     final int count = 5;
670     final AtomicInteger ran = new AtomicInteger(0);
671 jsr166 1.37 final ThreadPoolExecutor p =
672 jsr166 1.61 new ThreadPoolExecutor(poolSize, poolSize,
673 jsr166 1.37 LONG_DELAY_MS, MILLISECONDS,
674     new ArrayBlockingQueue<Runnable>(10));
675 jsr166 1.99 final CountDownLatch threadsStarted = new CountDownLatch(poolSize);
676 jsr166 1.63 Runnable waiter = new CheckedRunnable() { public void realRun() {
677 jsr166 1.61 threadsStarted.countDown();
678 dl 1.17 try {
679 jsr166 1.126 MILLISECONDS.sleep(LONGER_DELAY_MS);
680 jsr166 1.61 } catch (InterruptedException success) {}
681     ran.getAndIncrement();
682     }};
683     for (int i = 0; i < count; i++)
684     p.execute(waiter);
685 jsr166 1.107 await(threadsStarted);
686 jsr166 1.62 assertEquals(poolSize, p.getActiveCount());
687     assertEquals(0, p.getCompletedTaskCount());
688 jsr166 1.61 final List<Runnable> queuedTasks;
689     try {
690     queuedTasks = p.shutdownNow();
691     } catch (SecurityException ok) {
692     return; // Allowed in case test doesn't have privs
693 dl 1.1 }
694 jsr166 1.37 assertTrue(p.isShutdown());
695 jsr166 1.60 assertTrue(p.getQueue().isEmpty());
696 jsr166 1.61 assertEquals(count - poolSize, queuedTasks.size());
697     assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
698     assertTrue(p.isTerminated());
699     assertEquals(poolSize, ran.get());
700 jsr166 1.62 assertEquals(poolSize, p.getCompletedTaskCount());
701 dl 1.1 }
702    
703     // Exception Tests
704    
705 jsr166 1.24 /**
706     * Constructor throws if corePoolSize argument is less than zero
707 dl 1.6 */
708 dl 1.1 public void testConstructor1() {
709 dl 1.5 try {
710 jsr166 1.52 new ThreadPoolExecutor(-1, 1, 1L, SECONDS,
711 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10));
712 dl 1.5 shouldThrow();
713 jsr166 1.28 } catch (IllegalArgumentException success) {}
714 dl 1.1 }
715 jsr166 1.24
716     /**
717     * Constructor throws if maximumPoolSize is less than zero
718 dl 1.6 */
719 dl 1.1 public void testConstructor2() {
720 dl 1.5 try {
721 jsr166 1.52 new ThreadPoolExecutor(1, -1, 1L, SECONDS,
722 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10));
723 dl 1.5 shouldThrow();
724 jsr166 1.28 } catch (IllegalArgumentException success) {}
725 dl 1.1 }
726 jsr166 1.24
727     /**
728     * Constructor throws if maximumPoolSize is equal to zero
729 dl 1.6 */
730 dl 1.1 public void testConstructor3() {
731 dl 1.5 try {
732 jsr166 1.52 new ThreadPoolExecutor(1, 0, 1L, SECONDS,
733 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10));
734 dl 1.5 shouldThrow();
735 jsr166 1.28 } catch (IllegalArgumentException success) {}
736 dl 1.1 }
737    
738 jsr166 1.24 /**
739     * Constructor throws if keepAliveTime is less than zero
740 dl 1.6 */
741 dl 1.1 public void testConstructor4() {
742 dl 1.5 try {
743 jsr166 1.52 new ThreadPoolExecutor(1, 2, -1L, SECONDS,
744 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10));
745 dl 1.5 shouldThrow();
746 jsr166 1.28 } catch (IllegalArgumentException success) {}
747 dl 1.1 }
748    
749 jsr166 1.24 /**
750     * Constructor throws if corePoolSize is greater than the maximumPoolSize
751 dl 1.6 */
752 dl 1.1 public void testConstructor5() {
753 dl 1.5 try {
754 jsr166 1.52 new ThreadPoolExecutor(2, 1, 1L, SECONDS,
755 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10));
756 dl 1.5 shouldThrow();
757 jsr166 1.28 } catch (IllegalArgumentException success) {}
758 dl 1.1 }
759 jsr166 1.24
760     /**
761     * Constructor throws if workQueue is set to null
762 dl 1.6 */
763 dl 1.8 public void testConstructorNullPointerException() {
764 dl 1.5 try {
765 jsr166 1.52 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
766 dl 1.127 (BlockingQueue<Runnable>) null);
767 dl 1.5 shouldThrow();
768 jsr166 1.28 } catch (NullPointerException success) {}
769 dl 1.1 }
770    
771 jsr166 1.24 /**
772     * Constructor throws if corePoolSize argument is less than zero
773 dl 1.6 */
774 dl 1.1 public void testConstructor6() {
775 dl 1.5 try {
776 jsr166 1.52 new ThreadPoolExecutor(-1, 1, 1L, SECONDS,
777 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
778     new SimpleThreadFactory());
779 dl 1.5 shouldThrow();
780 jsr166 1.28 } catch (IllegalArgumentException success) {}
781 dl 1.1 }
782 jsr166 1.24
783     /**
784     * Constructor throws if maximumPoolSize is less than zero
785 dl 1.6 */
786 dl 1.1 public void testConstructor7() {
787 dl 1.5 try {
788 jsr166 1.52 new ThreadPoolExecutor(1, -1, 1L, SECONDS,
789 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
790     new SimpleThreadFactory());
791 dl 1.5 shouldThrow();
792 jsr166 1.28 } catch (IllegalArgumentException success) {}
793 dl 1.1 }
794    
795 jsr166 1.24 /**
796     * Constructor throws if maximumPoolSize is equal to zero
797 dl 1.6 */
798 dl 1.1 public void testConstructor8() {
799 dl 1.5 try {
800 jsr166 1.52 new ThreadPoolExecutor(1, 0, 1L, SECONDS,
801 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
802     new SimpleThreadFactory());
803 dl 1.5 shouldThrow();
804 jsr166 1.28 } catch (IllegalArgumentException success) {}
805 dl 1.1 }
806    
807 jsr166 1.24 /**
808     * Constructor throws if keepAliveTime is less than zero
809 dl 1.6 */
810 dl 1.1 public void testConstructor9() {
811 dl 1.5 try {
812 jsr166 1.52 new ThreadPoolExecutor(1, 2, -1L, SECONDS,
813 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
814     new SimpleThreadFactory());
815 dl 1.5 shouldThrow();
816 jsr166 1.28 } catch (IllegalArgumentException success) {}
817 dl 1.1 }
818    
819 jsr166 1.24 /**
820     * Constructor throws if corePoolSize is greater than the maximumPoolSize
821 dl 1.6 */
822 dl 1.1 public void testConstructor10() {
823 dl 1.5 try {
824 jsr166 1.52 new ThreadPoolExecutor(2, 1, 1L, SECONDS,
825 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
826     new SimpleThreadFactory());
827 dl 1.5 shouldThrow();
828 jsr166 1.28 } catch (IllegalArgumentException success) {}
829 dl 1.1 }
830    
831 jsr166 1.24 /**
832     * Constructor throws if workQueue is set to null
833 dl 1.6 */
834 dl 1.8 public void testConstructorNullPointerException2() {
835 dl 1.5 try {
836 jsr166 1.52 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
837 dl 1.127 (BlockingQueue<Runnable>) null,
838 jsr166 1.37 new SimpleThreadFactory());
839 dl 1.5 shouldThrow();
840 jsr166 1.28 } catch (NullPointerException success) {}
841 dl 1.1 }
842    
843 jsr166 1.24 /**
844     * Constructor throws if threadFactory is set to null
845 dl 1.6 */
846 dl 1.8 public void testConstructorNullPointerException3() {
847 dl 1.5 try {
848 jsr166 1.52 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
849 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
850     (ThreadFactory) null);
851 dl 1.5 shouldThrow();
852 jsr166 1.28 } catch (NullPointerException success) {}
853 dl 1.1 }
854 jsr166 1.24
855     /**
856     * Constructor throws if corePoolSize argument is less than zero
857 dl 1.6 */
858 dl 1.1 public void testConstructor11() {
859 dl 1.5 try {
860 jsr166 1.52 new ThreadPoolExecutor(-1, 1, 1L, SECONDS,
861 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
862     new NoOpREHandler());
863 dl 1.5 shouldThrow();
864 jsr166 1.28 } catch (IllegalArgumentException success) {}
865 dl 1.1 }
866    
867 jsr166 1.24 /**
868     * Constructor throws if maximumPoolSize is less than zero
869 dl 1.6 */
870 dl 1.1 public void testConstructor12() {
871 dl 1.5 try {
872 jsr166 1.52 new ThreadPoolExecutor(1, -1, 1L, SECONDS,
873 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
874     new NoOpREHandler());
875 dl 1.5 shouldThrow();
876 jsr166 1.28 } catch (IllegalArgumentException success) {}
877 dl 1.1 }
878    
879 jsr166 1.24 /**
880     * Constructor throws if maximumPoolSize is equal to zero
881 dl 1.6 */
882 dl 1.1 public void testConstructor13() {
883 dl 1.5 try {
884 jsr166 1.52 new ThreadPoolExecutor(1, 0, 1L, SECONDS,
885 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
886     new NoOpREHandler());
887 dl 1.5 shouldThrow();
888 jsr166 1.28 } catch (IllegalArgumentException success) {}
889 dl 1.1 }
890    
891 jsr166 1.24 /**
892     * Constructor throws if keepAliveTime is less than zero
893 dl 1.6 */
894 dl 1.1 public void testConstructor14() {
895 dl 1.5 try {
896 jsr166 1.52 new ThreadPoolExecutor(1, 2, -1L, SECONDS,
897 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
898     new NoOpREHandler());
899 dl 1.5 shouldThrow();
900 jsr166 1.28 } catch (IllegalArgumentException success) {}
901 dl 1.1 }
902    
903 jsr166 1.24 /**
904     * Constructor throws if corePoolSize is greater than the maximumPoolSize
905 dl 1.6 */
906 dl 1.1 public void testConstructor15() {
907 dl 1.5 try {
908 jsr166 1.52 new ThreadPoolExecutor(2, 1, 1L, SECONDS,
909 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
910     new NoOpREHandler());
911 dl 1.5 shouldThrow();
912 jsr166 1.28 } catch (IllegalArgumentException success) {}
913 dl 1.1 }
914    
915 jsr166 1.24 /**
916     * Constructor throws if workQueue is set to null
917 dl 1.6 */
918 dl 1.8 public void testConstructorNullPointerException4() {
919 dl 1.5 try {
920 jsr166 1.52 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
921 dl 1.127 (BlockingQueue<Runnable>) null,
922 jsr166 1.37 new NoOpREHandler());
923 dl 1.5 shouldThrow();
924 jsr166 1.28 } catch (NullPointerException success) {}
925 dl 1.1 }
926    
927 jsr166 1.24 /**
928     * Constructor throws if handler is set to null
929 dl 1.6 */
930 dl 1.8 public void testConstructorNullPointerException5() {
931 dl 1.5 try {
932 jsr166 1.52 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
933 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
934     (RejectedExecutionHandler) null);
935 dl 1.5 shouldThrow();
936 jsr166 1.28 } catch (NullPointerException success) {}
937 dl 1.1 }
938    
939 jsr166 1.24 /**
940     * Constructor throws if corePoolSize argument is less than zero
941 dl 1.6 */
942 dl 1.1 public void testConstructor16() {
943 dl 1.5 try {
944 jsr166 1.52 new ThreadPoolExecutor(-1, 1, 1L, SECONDS,
945 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
946     new SimpleThreadFactory(),
947     new NoOpREHandler());
948 dl 1.5 shouldThrow();
949 jsr166 1.28 } catch (IllegalArgumentException success) {}
950 dl 1.1 }
951    
952 jsr166 1.24 /**
953     * Constructor throws if maximumPoolSize is less than zero
954 dl 1.6 */
955 dl 1.1 public void testConstructor17() {
956 dl 1.5 try {
957 jsr166 1.52 new ThreadPoolExecutor(1, -1, 1L, SECONDS,
958 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
959     new SimpleThreadFactory(),
960     new NoOpREHandler());
961 dl 1.5 shouldThrow();
962 jsr166 1.28 } catch (IllegalArgumentException success) {}
963 dl 1.1 }
964    
965 jsr166 1.24 /**
966     * Constructor throws if maximumPoolSize is equal to zero
967 dl 1.6 */
968 dl 1.1 public void testConstructor18() {
969 dl 1.5 try {
970 jsr166 1.52 new ThreadPoolExecutor(1, 0, 1L, SECONDS,
971 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
972     new SimpleThreadFactory(),
973     new NoOpREHandler());
974 dl 1.5 shouldThrow();
975 jsr166 1.28 } catch (IllegalArgumentException success) {}
976 dl 1.1 }
977    
978 jsr166 1.24 /**
979     * Constructor throws if keepAliveTime is less than zero
980 dl 1.6 */
981 dl 1.1 public void testConstructor19() {
982 dl 1.5 try {
983 jsr166 1.52 new ThreadPoolExecutor(1, 2, -1L, SECONDS,
984 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
985     new SimpleThreadFactory(),
986     new NoOpREHandler());
987 dl 1.5 shouldThrow();
988 jsr166 1.28 } catch (IllegalArgumentException success) {}
989 dl 1.1 }
990    
991 jsr166 1.24 /**
992     * Constructor throws if corePoolSize is greater than the maximumPoolSize
993 dl 1.6 */
994 dl 1.1 public void testConstructor20() {
995 dl 1.5 try {
996 jsr166 1.52 new ThreadPoolExecutor(2, 1, 1L, SECONDS,
997 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
998     new SimpleThreadFactory(),
999     new NoOpREHandler());
1000 dl 1.5 shouldThrow();
1001 jsr166 1.28 } catch (IllegalArgumentException success) {}
1002 dl 1.1 }
1003    
1004 jsr166 1.24 /**
1005 jsr166 1.36 * Constructor throws if workQueue is null
1006 dl 1.6 */
1007 dl 1.8 public void testConstructorNullPointerException6() {
1008 dl 1.5 try {
1009 jsr166 1.52 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
1010 dl 1.127 (BlockingQueue<Runnable>) null,
1011 jsr166 1.37 new SimpleThreadFactory(),
1012     new NoOpREHandler());
1013 dl 1.5 shouldThrow();
1014 jsr166 1.28 } catch (NullPointerException success) {}
1015 dl 1.1 }
1016    
1017 jsr166 1.24 /**
1018 jsr166 1.36 * Constructor throws if handler is null
1019 dl 1.6 */
1020 dl 1.8 public void testConstructorNullPointerException7() {
1021 dl 1.5 try {
1022 jsr166 1.52 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
1023 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
1024     new SimpleThreadFactory(),
1025     (RejectedExecutionHandler) null);
1026 dl 1.5 shouldThrow();
1027 jsr166 1.28 } catch (NullPointerException success) {}
1028 dl 1.1 }
1029    
1030 jsr166 1.24 /**
1031 jsr166 1.36 * Constructor throws if ThreadFactory is null
1032 dl 1.6 */
1033 dl 1.8 public void testConstructorNullPointerException8() {
1034 dl 1.5 try {
1035 jsr166 1.52 new ThreadPoolExecutor(1, 2, 1L, SECONDS,
1036 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10),
1037     (ThreadFactory) null,
1038     new NoOpREHandler());
1039 dl 1.5 shouldThrow();
1040 jsr166 1.28 } catch (NullPointerException success) {}
1041 dl 1.1 }
1042 jsr166 1.24
1043 jsr166 1.37 /**
1044     * get of submitted callable throws InterruptedException if interrupted
1045     */
1046     public void testInterruptedSubmit() throws InterruptedException {
1047 jsr166 1.104 final CountDownLatch done = new CountDownLatch(1);
1048 jsr166 1.37 final ThreadPoolExecutor p =
1049     new ThreadPoolExecutor(1, 1,
1050 jsr166 1.55 60, SECONDS,
1051 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10));
1052    
1053 jsr166 1.104 try (PoolCleaner cleaner = cleaner(p, done)) {
1054 jsr166 1.88 final CountDownLatch threadStarted = new CountDownLatch(1);
1055 jsr166 1.37 Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1056     public void realRun() throws Exception {
1057 jsr166 1.128 Callable<Boolean> task = new CheckedCallable<>() {
1058 jsr166 1.37 public Boolean realCall() throws InterruptedException {
1059     threadStarted.countDown();
1060 jsr166 1.106 await(done);
1061 jsr166 1.37 return Boolean.TRUE;
1062     }};
1063     p.submit(task).get();
1064     }});
1065    
1066 jsr166 1.124 await(threadStarted); // ensure quiescence
1067 jsr166 1.37 t.interrupt();
1068 jsr166 1.104 awaitTermination(t);
1069 jsr166 1.37 }
1070     }
1071 dl 1.1
1072     /**
1073 jsr166 1.124 * Submitted tasks are rejected when saturated or shutdown
1074 dl 1.8 */
1075 jsr166 1.124 public void testSubmittedTasksRejectedWhenSaturatedOrShutdown() throws InterruptedException {
1076     final ThreadPoolExecutor p = new ThreadPoolExecutor(
1077     1, 1, 1, SECONDS, new ArrayBlockingQueue<Runnable>(1));
1078     final int saturatedSize = saturatedSize(p);
1079 jsr166 1.123 final ThreadLocalRandom rnd = ThreadLocalRandom.current();
1080 jsr166 1.124 final CountDownLatch threadsStarted = new CountDownLatch(p.getMaximumPoolSize());
1081 jsr166 1.109 final CountDownLatch done = new CountDownLatch(1);
1082 jsr166 1.124 final Runnable r = () -> {
1083     threadsStarted.countDown();
1084     for (;;) {
1085     try {
1086     done.await();
1087     return;
1088     } catch (InterruptedException shutdownNowDeliberatelyIgnored) {}
1089     }};
1090     final Callable<Boolean> c = () -> {
1091     threadsStarted.countDown();
1092     for (;;) {
1093     try {
1094     done.await();
1095     return Boolean.TRUE;
1096     } catch (InterruptedException shutdownNowDeliberatelyIgnored) {}
1097 jsr166 1.123 }};
1098 jsr166 1.124 final boolean shutdownNow = rnd.nextBoolean();
1099 jsr166 1.123
1100 jsr166 1.109 try (PoolCleaner cleaner = cleaner(p, done)) {
1101 jsr166 1.123 // saturate
1102 jsr166 1.124 for (int i = saturatedSize; i--> 0; ) {
1103     switch (rnd.nextInt(4)) {
1104 jsr166 1.123 case 0: p.execute(r); break;
1105     case 1: assertFalse(p.submit(r).isDone()); break;
1106 jsr166 1.124 case 2: assertFalse(p.submit(r, Boolean.TRUE).isDone()); break;
1107     case 3: assertFalse(p.submit(c).isDone()); break;
1108 jsr166 1.123 }
1109     }
1110    
1111 jsr166 1.124 await(threadsStarted);
1112     assertTaskSubmissionsAreRejected(p);
1113 jsr166 1.123
1114 jsr166 1.124 if (shutdownNow)
1115     p.shutdownNow();
1116     else
1117     p.shutdown();
1118     // Pool is shutdown, but not yet terminated
1119     assertTaskSubmissionsAreRejected(p);
1120     assertFalse(p.isTerminated());
1121    
1122     done.countDown(); // release blocking tasks
1123     assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
1124    
1125     assertTaskSubmissionsAreRejected(p);
1126     }
1127     assertEquals(saturatedSize(p)
1128     - (shutdownNow ? p.getQueue().remainingCapacity() : 0),
1129     p.getCompletedTaskCount());
1130 dl 1.8 }
1131    
1132     /**
1133 jsr166 1.35 * executor using DiscardOldestPolicy drops oldest task if saturated.
1134 dl 1.8 */
1135 jsr166 1.124 public void testSaturatedExecute_DiscardOldestPolicy() {
1136 jsr166 1.92 final CountDownLatch done = new CountDownLatch(1);
1137     LatchAwaiter r1 = awaiter(done);
1138     LatchAwaiter r2 = awaiter(done);
1139     LatchAwaiter r3 = awaiter(done);
1140 jsr166 1.37 final ThreadPoolExecutor p =
1141     new ThreadPoolExecutor(1, 1,
1142     LONG_DELAY_MS, MILLISECONDS,
1143     new ArrayBlockingQueue<Runnable>(1),
1144 jsr166 1.121 new DiscardOldestPolicy());
1145 jsr166 1.109 try (PoolCleaner cleaner = cleaner(p, done)) {
1146 jsr166 1.92 assertEquals(LatchAwaiter.NEW, r1.state);
1147     assertEquals(LatchAwaiter.NEW, r2.state);
1148     assertEquals(LatchAwaiter.NEW, r3.state);
1149     p.execute(r1);
1150 dl 1.8 p.execute(r2);
1151     assertTrue(p.getQueue().contains(r2));
1152     p.execute(r3);
1153     assertFalse(p.getQueue().contains(r2));
1154     assertTrue(p.getQueue().contains(r3));
1155     }
1156 jsr166 1.92 assertEquals(LatchAwaiter.DONE, r1.state);
1157     assertEquals(LatchAwaiter.NEW, r2.state);
1158     assertEquals(LatchAwaiter.DONE, r3.state);
1159 dl 1.8 }
1160    
1161     /**
1162 jsr166 1.35 * execute using DiscardOldestPolicy drops task on shutdown
1163 dl 1.6 */
1164 dl 1.8 public void testDiscardOldestOnShutdown() {
1165 jsr166 1.95 final ThreadPoolExecutor p =
1166 jsr166 1.37 new ThreadPoolExecutor(1, 1,
1167     LONG_DELAY_MS, MILLISECONDS,
1168     new ArrayBlockingQueue<Runnable>(1),
1169 jsr166 1.121 new DiscardOldestPolicy());
1170 dl 1.8
1171 jsr166 1.25 try { p.shutdown(); } catch (SecurityException ok) { return; }
1172 jsr166 1.95 try (PoolCleaner cleaner = cleaner(p)) {
1173 dl 1.8 TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1174 jsr166 1.31 p.execute(r);
1175 dl 1.8 assertFalse(r.done);
1176     }
1177 dl 1.6 }
1178    
1179     /**
1180 jsr166 1.124 * Submitting null tasks throws NullPointerException
1181 dl 1.6 */
1182 jsr166 1.124 public void testNullTaskSubmission() {
1183 jsr166 1.95 final ThreadPoolExecutor p =
1184     new ThreadPoolExecutor(1, 2,
1185     1L, SECONDS,
1186 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10));
1187 jsr166 1.95 try (PoolCleaner cleaner = cleaner(p)) {
1188 jsr166 1.124 assertNullTaskSubmissionThrowsNullPointerException(p);
1189 jsr166 1.95 }
1190 dl 1.6 }
1191 jsr166 1.24
1192 dl 1.1 /**
1193 jsr166 1.34 * setCorePoolSize of negative value throws IllegalArgumentException
1194 dl 1.1 */
1195 dl 1.5 public void testCorePoolSizeIllegalArgumentException() {
1196 jsr166 1.96 final ThreadPoolExecutor p =
1197 jsr166 1.27 new ThreadPoolExecutor(1, 2,
1198     LONG_DELAY_MS, MILLISECONDS,
1199     new ArrayBlockingQueue<Runnable>(10));
1200 jsr166 1.97 try (PoolCleaner cleaner = cleaner(p)) {
1201     try {
1202     p.setCorePoolSize(-1);
1203     shouldThrow();
1204     } catch (IllegalArgumentException success) {}
1205 dl 1.1 }
1206 jsr166 1.24 }
1207 dl 1.1
1208     /**
1209 jsr166 1.35 * setMaximumPoolSize(int) throws IllegalArgumentException if
1210     * given a value less the core pool size
1211 jsr166 1.24 */
1212 dl 1.5 public void testMaximumPoolSizeIllegalArgumentException() {
1213 jsr166 1.96 final ThreadPoolExecutor p =
1214 jsr166 1.27 new ThreadPoolExecutor(2, 3,
1215     LONG_DELAY_MS, MILLISECONDS,
1216     new ArrayBlockingQueue<Runnable>(10));
1217 jsr166 1.98 try (PoolCleaner cleaner = cleaner(p)) {
1218     try {
1219     p.setMaximumPoolSize(1);
1220     shouldThrow();
1221     } catch (IllegalArgumentException success) {}
1222 dl 1.1 }
1223     }
1224 jsr166 1.24
1225 dl 1.1 /**
1226 jsr166 1.35 * setMaximumPoolSize throws IllegalArgumentException
1227     * if given a negative value
1228 dl 1.1 */
1229 dl 1.5 public void testMaximumPoolSizeIllegalArgumentException2() {
1230 jsr166 1.96 final ThreadPoolExecutor p =
1231 jsr166 1.27 new ThreadPoolExecutor(2, 3,
1232     LONG_DELAY_MS, MILLISECONDS,
1233     new ArrayBlockingQueue<Runnable>(10));
1234 jsr166 1.98 try (PoolCleaner cleaner = cleaner(p)) {
1235     try {
1236     p.setMaximumPoolSize(-1);
1237     shouldThrow();
1238     } catch (IllegalArgumentException success) {}
1239 dl 1.1 }
1240     }
1241 jsr166 1.24
1242 dl 1.1 /**
1243 jsr166 1.54 * Configuration changes that allow core pool size greater than
1244     * max pool size result in IllegalArgumentException.
1245     */
1246     public void testPoolSizeInvariants() {
1247 jsr166 1.96 final ThreadPoolExecutor p =
1248 jsr166 1.54 new ThreadPoolExecutor(1, 1,
1249     LONG_DELAY_MS, MILLISECONDS,
1250     new ArrayBlockingQueue<Runnable>(10));
1251 jsr166 1.98 try (PoolCleaner cleaner = cleaner(p)) {
1252     for (int s = 1; s < 5; s++) {
1253     p.setMaximumPoolSize(s);
1254     p.setCorePoolSize(s);
1255     try {
1256     p.setMaximumPoolSize(s - 1);
1257     shouldThrow();
1258     } catch (IllegalArgumentException success) {}
1259     assertEquals(s, p.getCorePoolSize());
1260     assertEquals(s, p.getMaximumPoolSize());
1261     try {
1262     p.setCorePoolSize(s + 1);
1263     shouldThrow();
1264     } catch (IllegalArgumentException success) {}
1265     assertEquals(s, p.getCorePoolSize());
1266     assertEquals(s, p.getMaximumPoolSize());
1267     }
1268 jsr166 1.54 }
1269     }
1270    
1271     /**
1272 jsr166 1.35 * setKeepAliveTime throws IllegalArgumentException
1273     * when given a negative value
1274 dl 1.1 */
1275 dl 1.5 public void testKeepAliveTimeIllegalArgumentException() {
1276 jsr166 1.96 final ThreadPoolExecutor p =
1277 jsr166 1.27 new ThreadPoolExecutor(2, 3,
1278     LONG_DELAY_MS, MILLISECONDS,
1279     new ArrayBlockingQueue<Runnable>(10));
1280 jsr166 1.98 try (PoolCleaner cleaner = cleaner(p)) {
1281     try {
1282     p.setKeepAliveTime(-1, MILLISECONDS);
1283     shouldThrow();
1284     } catch (IllegalArgumentException success) {}
1285 dl 1.1 }
1286     }
1287 dl 1.8
1288     /**
1289     * terminated() is called on termination
1290     */
1291     public void testTerminated() {
1292 jsr166 1.37 ExtendedTPE p = new ExtendedTPE();
1293 jsr166 1.98 try (PoolCleaner cleaner = cleaner(p)) {
1294     try { p.shutdown(); } catch (SecurityException ok) { return; }
1295     assertTrue(p.terminatedCalled());
1296     assertTrue(p.isShutdown());
1297     }
1298 dl 1.8 }
1299    
1300     /**
1301     * beforeExecute and afterExecute are called when executing task
1302     */
1303 jsr166 1.27 public void testBeforeAfter() throws InterruptedException {
1304 jsr166 1.37 ExtendedTPE p = new ExtendedTPE();
1305 jsr166 1.98 try (PoolCleaner cleaner = cleaner(p)) {
1306 jsr166 1.45 final CountDownLatch done = new CountDownLatch(1);
1307 jsr166 1.49 p.execute(new CheckedRunnable() {
1308 jsr166 1.45 public void realRun() {
1309     done.countDown();
1310 jsr166 1.49 }});
1311 jsr166 1.45 await(p.afterCalled);
1312     assertEquals(0, done.getCount());
1313     assertTrue(p.afterCalled());
1314     assertTrue(p.beforeCalled());
1315 dl 1.8 }
1316     }
1317 dl 1.12
1318     /**
1319     * completed submit of callable returns result
1320     */
1321 jsr166 1.27 public void testSubmitCallable() throws Exception {
1322 jsr166 1.98 final ExecutorService e =
1323 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1324     LONG_DELAY_MS, MILLISECONDS,
1325     new ArrayBlockingQueue<Runnable>(10));
1326 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1327 dl 1.12 Future<String> future = e.submit(new StringTask());
1328     String result = future.get();
1329     assertSame(TEST_STRING, result);
1330     }
1331     }
1332    
1333     /**
1334     * completed submit of runnable returns successfully
1335     */
1336 jsr166 1.27 public void testSubmitRunnable() throws Exception {
1337 jsr166 1.98 final ExecutorService e =
1338 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1339     LONG_DELAY_MS, MILLISECONDS,
1340     new ArrayBlockingQueue<Runnable>(10));
1341 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1342 dl 1.12 Future<?> future = e.submit(new NoOpRunnable());
1343     future.get();
1344     assertTrue(future.isDone());
1345     }
1346     }
1347    
1348     /**
1349     * completed submit of (runnable, result) returns result
1350     */
1351 jsr166 1.27 public void testSubmitRunnable2() throws Exception {
1352 jsr166 1.98 final ExecutorService e =
1353 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1354     LONG_DELAY_MS, MILLISECONDS,
1355     new ArrayBlockingQueue<Runnable>(10));
1356 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1357 dl 1.12 Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
1358     String result = future.get();
1359     assertSame(TEST_STRING, result);
1360     }
1361     }
1362    
1363     /**
1364     * invokeAny(null) throws NPE
1365     */
1366 jsr166 1.27 public void testInvokeAny1() throws Exception {
1367 jsr166 1.98 final ExecutorService e =
1368 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1369     LONG_DELAY_MS, MILLISECONDS,
1370     new ArrayBlockingQueue<Runnable>(10));
1371 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1372     try {
1373     e.invokeAny(null);
1374     shouldThrow();
1375     } catch (NullPointerException success) {}
1376 dl 1.12 }
1377     }
1378    
1379     /**
1380 jsr166 1.119 * invokeAny(empty collection) throws IllegalArgumentException
1381 dl 1.12 */
1382 jsr166 1.27 public void testInvokeAny2() throws Exception {
1383 jsr166 1.98 final ExecutorService e =
1384 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1385     LONG_DELAY_MS, MILLISECONDS,
1386     new ArrayBlockingQueue<Runnable>(10));
1387 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1388     try {
1389     e.invokeAny(new ArrayList<Callable<String>>());
1390     shouldThrow();
1391     } catch (IllegalArgumentException success) {}
1392 dl 1.12 }
1393     }
1394    
1395     /**
1396     * invokeAny(c) throws NPE if c has null elements
1397     */
1398 jsr166 1.27 public void testInvokeAny3() throws Exception {
1399 jsr166 1.37 final CountDownLatch latch = new CountDownLatch(1);
1400     final ExecutorService e =
1401     new ThreadPoolExecutor(2, 2,
1402     LONG_DELAY_MS, MILLISECONDS,
1403     new ArrayBlockingQueue<Runnable>(10));
1404 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1405 jsr166 1.114 List<Callable<String>> l = new ArrayList<>();
1406 jsr166 1.98 l.add(latchAwaitingStringTask(latch));
1407     l.add(null);
1408     try {
1409     e.invokeAny(l);
1410     shouldThrow();
1411     } catch (NullPointerException success) {}
1412 jsr166 1.27 latch.countDown();
1413 dl 1.12 }
1414     }
1415    
1416     /**
1417     * invokeAny(c) throws ExecutionException if no task completes
1418     */
1419 jsr166 1.27 public void testInvokeAny4() throws Exception {
1420 jsr166 1.98 final ExecutorService e =
1421 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1422     LONG_DELAY_MS, MILLISECONDS,
1423     new ArrayBlockingQueue<Runnable>(10));
1424 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1425 jsr166 1.114 List<Callable<String>> l = new ArrayList<>();
1426 jsr166 1.98 l.add(new NPETask());
1427     try {
1428     e.invokeAny(l);
1429     shouldThrow();
1430     } catch (ExecutionException success) {
1431     assertTrue(success.getCause() instanceof NullPointerException);
1432     }
1433 dl 1.12 }
1434     }
1435    
1436     /**
1437     * invokeAny(c) returns result of some task
1438     */
1439 jsr166 1.27 public void testInvokeAny5() throws Exception {
1440 jsr166 1.98 final ExecutorService e =
1441 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1442     LONG_DELAY_MS, MILLISECONDS,
1443     new ArrayBlockingQueue<Runnable>(10));
1444 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1445 jsr166 1.114 List<Callable<String>> l = new ArrayList<>();
1446 dl 1.12 l.add(new StringTask());
1447     l.add(new StringTask());
1448     String result = e.invokeAny(l);
1449     assertSame(TEST_STRING, result);
1450     }
1451     }
1452    
1453     /**
1454     * invokeAll(null) throws NPE
1455     */
1456 jsr166 1.27 public void testInvokeAll1() throws Exception {
1457 jsr166 1.98 final ExecutorService e =
1458 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1459     LONG_DELAY_MS, MILLISECONDS,
1460     new ArrayBlockingQueue<Runnable>(10));
1461 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1462     try {
1463     e.invokeAll(null);
1464     shouldThrow();
1465     } catch (NullPointerException success) {}
1466 dl 1.12 }
1467     }
1468    
1469     /**
1470 jsr166 1.119 * invokeAll(empty collection) returns empty list
1471 dl 1.12 */
1472 jsr166 1.27 public void testInvokeAll2() throws InterruptedException {
1473 jsr166 1.98 final ExecutorService e =
1474 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1475     LONG_DELAY_MS, MILLISECONDS,
1476     new ArrayBlockingQueue<Runnable>(10));
1477 jsr166 1.119 final Collection<Callable<String>> emptyCollection
1478     = Collections.emptyList();
1479 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1480 jsr166 1.119 List<Future<String>> r = e.invokeAll(emptyCollection);
1481 dl 1.12 assertTrue(r.isEmpty());
1482     }
1483     }
1484    
1485     /**
1486     * invokeAll(c) throws NPE if c has null elements
1487     */
1488 jsr166 1.27 public void testInvokeAll3() throws Exception {
1489 jsr166 1.98 final ExecutorService e =
1490 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1491     LONG_DELAY_MS, MILLISECONDS,
1492     new ArrayBlockingQueue<Runnable>(10));
1493 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1494 jsr166 1.114 List<Callable<String>> l = new ArrayList<>();
1495 jsr166 1.98 l.add(new StringTask());
1496     l.add(null);
1497     try {
1498     e.invokeAll(l);
1499     shouldThrow();
1500     } catch (NullPointerException success) {}
1501 dl 1.12 }
1502     }
1503    
1504     /**
1505     * get of element of invokeAll(c) throws exception on failed task
1506     */
1507 jsr166 1.27 public void testInvokeAll4() throws Exception {
1508 jsr166 1.98 final ExecutorService e =
1509 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1510     LONG_DELAY_MS, MILLISECONDS,
1511     new ArrayBlockingQueue<Runnable>(10));
1512 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1513 jsr166 1.114 List<Callable<String>> l = new ArrayList<>();
1514 dl 1.12 l.add(new NPETask());
1515 jsr166 1.33 List<Future<String>> futures = e.invokeAll(l);
1516     assertEquals(1, futures.size());
1517     try {
1518     futures.get(0).get();
1519     shouldThrow();
1520     } catch (ExecutionException success) {
1521     assertTrue(success.getCause() instanceof NullPointerException);
1522 jsr166 1.27 }
1523 dl 1.12 }
1524     }
1525    
1526     /**
1527     * invokeAll(c) returns results of all completed tasks
1528     */
1529 jsr166 1.27 public void testInvokeAll5() throws Exception {
1530 jsr166 1.98 final ExecutorService e =
1531 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1532     LONG_DELAY_MS, MILLISECONDS,
1533     new ArrayBlockingQueue<Runnable>(10));
1534 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1535 jsr166 1.114 List<Callable<String>> l = new ArrayList<>();
1536 dl 1.12 l.add(new StringTask());
1537     l.add(new StringTask());
1538 jsr166 1.33 List<Future<String>> futures = e.invokeAll(l);
1539     assertEquals(2, futures.size());
1540     for (Future<String> future : futures)
1541 jsr166 1.27 assertSame(TEST_STRING, future.get());
1542 dl 1.12 }
1543     }
1544    
1545 dl 1.13 /**
1546     * timed invokeAny(null) throws NPE
1547     */
1548 jsr166 1.27 public void testTimedInvokeAny1() throws Exception {
1549 jsr166 1.98 final ExecutorService e =
1550 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1551     LONG_DELAY_MS, MILLISECONDS,
1552     new ArrayBlockingQueue<Runnable>(10));
1553 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1554     try {
1555 jsr166 1.119 e.invokeAny(null, randomTimeout(), randomTimeUnit());
1556 jsr166 1.98 shouldThrow();
1557     } catch (NullPointerException success) {}
1558 dl 1.13 }
1559     }
1560    
1561     /**
1562     * timed invokeAny(,,null) throws NPE
1563     */
1564 jsr166 1.27 public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1565 jsr166 1.98 final ExecutorService e =
1566 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1567     LONG_DELAY_MS, MILLISECONDS,
1568     new ArrayBlockingQueue<Runnable>(10));
1569 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1570 jsr166 1.114 List<Callable<String>> l = new ArrayList<>();
1571 jsr166 1.98 l.add(new StringTask());
1572     try {
1573 jsr166 1.119 e.invokeAny(l, randomTimeout(), null);
1574 jsr166 1.98 shouldThrow();
1575     } catch (NullPointerException success) {}
1576 dl 1.13 }
1577     }
1578    
1579     /**
1580 jsr166 1.119 * timed invokeAny(empty collection) throws IllegalArgumentException
1581 dl 1.13 */
1582 jsr166 1.27 public void testTimedInvokeAny2() throws Exception {
1583 jsr166 1.98 final ExecutorService e =
1584 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1585     LONG_DELAY_MS, MILLISECONDS,
1586     new ArrayBlockingQueue<Runnable>(10));
1587 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1588     try {
1589     e.invokeAny(new ArrayList<Callable<String>>(),
1590 jsr166 1.119 randomTimeout(), randomTimeUnit());
1591 jsr166 1.98 shouldThrow();
1592     } catch (IllegalArgumentException success) {}
1593 dl 1.13 }
1594     }
1595    
1596     /**
1597 jsr166 1.119 * timed invokeAny(c) throws NullPointerException if c has null elements
1598 dl 1.13 */
1599 jsr166 1.27 public void testTimedInvokeAny3() throws Exception {
1600 jsr166 1.37 final CountDownLatch latch = new CountDownLatch(1);
1601     final ExecutorService e =
1602     new ThreadPoolExecutor(2, 2,
1603     LONG_DELAY_MS, MILLISECONDS,
1604     new ArrayBlockingQueue<Runnable>(10));
1605 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1606 jsr166 1.114 List<Callable<String>> l = new ArrayList<>();
1607 jsr166 1.98 l.add(latchAwaitingStringTask(latch));
1608     l.add(null);
1609     try {
1610 jsr166 1.119 e.invokeAny(l, randomTimeout(), randomTimeUnit());
1611 jsr166 1.98 shouldThrow();
1612     } catch (NullPointerException success) {}
1613 jsr166 1.30 latch.countDown();
1614 dl 1.13 }
1615     }
1616    
1617     /**
1618     * timed invokeAny(c) throws ExecutionException if no task completes
1619     */
1620 jsr166 1.27 public void testTimedInvokeAny4() throws Exception {
1621 jsr166 1.98 final ExecutorService e =
1622 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1623     LONG_DELAY_MS, MILLISECONDS,
1624     new ArrayBlockingQueue<Runnable>(10));
1625 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1626 jsr166 1.111 long startTime = System.nanoTime();
1627 jsr166 1.114 List<Callable<String>> l = new ArrayList<>();
1628 jsr166 1.98 l.add(new NPETask());
1629     try {
1630 jsr166 1.111 e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1631 jsr166 1.98 shouldThrow();
1632     } catch (ExecutionException success) {
1633     assertTrue(success.getCause() instanceof NullPointerException);
1634     }
1635 jsr166 1.111 assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1636 dl 1.13 }
1637     }
1638    
1639     /**
1640     * timed invokeAny(c) returns result of some task
1641     */
1642 jsr166 1.27 public void testTimedInvokeAny5() throws Exception {
1643 jsr166 1.98 final ExecutorService e =
1644 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1645     LONG_DELAY_MS, MILLISECONDS,
1646     new ArrayBlockingQueue<Runnable>(10));
1647 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1648 jsr166 1.112 long startTime = System.nanoTime();
1649 jsr166 1.114 List<Callable<String>> l = new ArrayList<>();
1650 dl 1.13 l.add(new StringTask());
1651     l.add(new StringTask());
1652 jsr166 1.112 String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1653 dl 1.13 assertSame(TEST_STRING, result);
1654 jsr166 1.112 assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1655 dl 1.13 }
1656     }
1657    
1658     /**
1659     * timed invokeAll(null) throws NPE
1660     */
1661 jsr166 1.27 public void testTimedInvokeAll1() throws Exception {
1662 jsr166 1.98 final ExecutorService e =
1663 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1664     LONG_DELAY_MS, MILLISECONDS,
1665     new ArrayBlockingQueue<Runnable>(10));
1666 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1667     try {
1668 jsr166 1.119 e.invokeAll(null, randomTimeout(), randomTimeUnit());
1669 jsr166 1.98 shouldThrow();
1670     } catch (NullPointerException success) {}
1671 dl 1.13 }
1672     }
1673    
1674     /**
1675     * timed invokeAll(,,null) throws NPE
1676     */
1677 jsr166 1.27 public void testTimedInvokeAllNullTimeUnit() throws Exception {
1678 jsr166 1.98 final ExecutorService e =
1679 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1680     LONG_DELAY_MS, MILLISECONDS,
1681     new ArrayBlockingQueue<Runnable>(10));
1682 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1683 jsr166 1.114 List<Callable<String>> l = new ArrayList<>();
1684 jsr166 1.98 l.add(new StringTask());
1685     try {
1686 jsr166 1.119 e.invokeAll(l, randomTimeout(), null);
1687 jsr166 1.98 shouldThrow();
1688     } catch (NullPointerException success) {}
1689 dl 1.13 }
1690     }
1691    
1692     /**
1693 jsr166 1.119 * timed invokeAll(empty collection) returns empty list
1694 dl 1.13 */
1695 jsr166 1.27 public void testTimedInvokeAll2() throws InterruptedException {
1696 jsr166 1.98 final ExecutorService e =
1697 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1698     LONG_DELAY_MS, MILLISECONDS,
1699     new ArrayBlockingQueue<Runnable>(10));
1700 jsr166 1.119 final Collection<Callable<String>> emptyCollection
1701     = Collections.emptyList();
1702 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1703 jsr166 1.119 List<Future<String>> r =
1704     e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit());
1705 dl 1.13 assertTrue(r.isEmpty());
1706     }
1707     }
1708    
1709     /**
1710     * timed invokeAll(c) throws NPE if c has null elements
1711     */
1712 jsr166 1.27 public void testTimedInvokeAll3() throws Exception {
1713 jsr166 1.98 final ExecutorService e =
1714 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1715     LONG_DELAY_MS, MILLISECONDS,
1716     new ArrayBlockingQueue<Runnable>(10));
1717 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1718 jsr166 1.114 List<Callable<String>> l = new ArrayList<>();
1719 jsr166 1.98 l.add(new StringTask());
1720     l.add(null);
1721     try {
1722 jsr166 1.119 e.invokeAll(l, randomTimeout(), randomTimeUnit());
1723 jsr166 1.98 shouldThrow();
1724     } catch (NullPointerException success) {}
1725 dl 1.13 }
1726     }
1727    
1728     /**
1729     * get of element of invokeAll(c) throws exception on failed task
1730     */
1731 jsr166 1.27 public void testTimedInvokeAll4() throws Exception {
1732 jsr166 1.98 final ExecutorService e =
1733 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1734     LONG_DELAY_MS, MILLISECONDS,
1735     new ArrayBlockingQueue<Runnable>(10));
1736 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1737 jsr166 1.114 List<Callable<String>> l = new ArrayList<>();
1738 jsr166 1.98 l.add(new NPETask());
1739     List<Future<String>> futures =
1740 jsr166 1.105 e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1741 jsr166 1.98 assertEquals(1, futures.size());
1742     try {
1743     futures.get(0).get();
1744     shouldThrow();
1745     } catch (ExecutionException success) {
1746     assertTrue(success.getCause() instanceof NullPointerException);
1747     }
1748 dl 1.13 }
1749     }
1750    
1751     /**
1752     * timed invokeAll(c) returns results of all completed tasks
1753     */
1754 jsr166 1.27 public void testTimedInvokeAll5() throws Exception {
1755 jsr166 1.98 final ExecutorService e =
1756 jsr166 1.37 new ThreadPoolExecutor(2, 2,
1757     LONG_DELAY_MS, MILLISECONDS,
1758     new ArrayBlockingQueue<Runnable>(10));
1759 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1760 jsr166 1.114 List<Callable<String>> l = new ArrayList<>();
1761 dl 1.13 l.add(new StringTask());
1762     l.add(new StringTask());
1763 jsr166 1.33 List<Future<String>> futures =
1764 jsr166 1.65 e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1765 jsr166 1.33 assertEquals(2, futures.size());
1766     for (Future<String> future : futures)
1767     assertSame(TEST_STRING, future.get());
1768 dl 1.13 }
1769     }
1770    
1771     /**
1772     * timed invokeAll(c) cancels tasks not completed by timeout
1773     */
1774 jsr166 1.27 public void testTimedInvokeAll6() throws Exception {
1775 jsr166 1.110 for (long timeout = timeoutMillis();;) {
1776     final CountDownLatch done = new CountDownLatch(1);
1777 jsr166 1.128 final Callable<String> waiter = new CheckedCallable<>() {
1778 jsr166 1.110 public String realCall() {
1779     try { done.await(LONG_DELAY_MS, MILLISECONDS); }
1780     catch (InterruptedException ok) {}
1781     return "1"; }};
1782     final ExecutorService p =
1783     new ThreadPoolExecutor(2, 2,
1784     LONG_DELAY_MS, MILLISECONDS,
1785     new ArrayBlockingQueue<Runnable>(10));
1786     try (PoolCleaner cleaner = cleaner(p, done)) {
1787 jsr166 1.56 List<Callable<String>> tasks = new ArrayList<>();
1788 jsr166 1.59 tasks.add(new StringTask("0"));
1789 jsr166 1.110 tasks.add(waiter);
1790 jsr166 1.59 tasks.add(new StringTask("2"));
1791 jsr166 1.56 long startTime = System.nanoTime();
1792     List<Future<String>> futures =
1793 jsr166 1.110 p.invokeAll(tasks, timeout, MILLISECONDS);
1794 jsr166 1.56 assertEquals(tasks.size(), futures.size());
1795     assertTrue(millisElapsedSince(startTime) >= timeout);
1796 dl 1.127 for (Future<?> future : futures)
1797 jsr166 1.56 assertTrue(future.isDone());
1798     assertTrue(futures.get(1).isCancelled());
1799     try {
1800 jsr166 1.59 assertEquals("0", futures.get(0).get());
1801     assertEquals("2", futures.get(2).get());
1802 jsr166 1.56 break;
1803     } catch (CancellationException retryWithLongerTimeout) {
1804     timeout *= 2;
1805     if (timeout >= LONG_DELAY_MS / 2)
1806     fail("expected exactly one task to be cancelled");
1807     }
1808     }
1809 dl 1.13 }
1810     }
1811    
1812 dl 1.19 /**
1813     * Execution continues if there is at least one thread even if
1814     * thread factory fails to create more
1815     */
1816 jsr166 1.27 public void testFailingThreadFactory() throws InterruptedException {
1817 jsr166 1.37 final ExecutorService e =
1818     new ThreadPoolExecutor(100, 100,
1819     LONG_DELAY_MS, MILLISECONDS,
1820     new LinkedBlockingQueue<Runnable>(),
1821     new FailingThreadFactory());
1822 jsr166 1.98 try (PoolCleaner cleaner = cleaner(e)) {
1823 jsr166 1.37 final int TASKS = 100;
1824     final CountDownLatch done = new CountDownLatch(TASKS);
1825     for (int k = 0; k < TASKS; ++k)
1826     e.execute(new CheckedRunnable() {
1827     public void realRun() {
1828     done.countDown();
1829     }});
1830 jsr166 1.117 await(done);
1831 dl 1.19 }
1832     }
1833 dl 1.21
1834     /**
1835     * allowsCoreThreadTimeOut is by default false.
1836     */
1837     public void testAllowsCoreThreadTimeOut() {
1838 jsr166 1.37 final ThreadPoolExecutor p =
1839     new ThreadPoolExecutor(2, 2,
1840     1000, MILLISECONDS,
1841     new ArrayBlockingQueue<Runnable>(10));
1842 jsr166 1.98 try (PoolCleaner cleaner = cleaner(p)) {
1843     assertFalse(p.allowsCoreThreadTimeOut());
1844     }
1845 dl 1.21 }
1846    
1847     /**
1848     * allowCoreThreadTimeOut(true) causes idle threads to time out
1849     */
1850 jsr166 1.37 public void testAllowCoreThreadTimeOut_true() throws Exception {
1851 jsr166 1.57 long keepAliveTime = timeoutMillis();
1852 jsr166 1.37 final ThreadPoolExecutor p =
1853     new ThreadPoolExecutor(2, 10,
1854 jsr166 1.57 keepAliveTime, MILLISECONDS,
1855 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10));
1856 jsr166 1.98 try (PoolCleaner cleaner = cleaner(p)) {
1857     final CountDownLatch threadStarted = new CountDownLatch(1);
1858 jsr166 1.37 p.allowCoreThreadTimeOut(true);
1859     p.execute(new CheckedRunnable() {
1860 jsr166 1.44 public void realRun() {
1861 jsr166 1.37 threadStarted.countDown();
1862     assertEquals(1, p.getPoolSize());
1863     }});
1864 jsr166 1.44 await(threadStarted);
1865 jsr166 1.57 delay(keepAliveTime);
1866 jsr166 1.44 long startTime = System.nanoTime();
1867     while (p.getPoolSize() > 0
1868     && millisElapsedSince(startTime) < LONG_DELAY_MS)
1869     Thread.yield();
1870     assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1871 jsr166 1.37 assertEquals(0, p.getPoolSize());
1872 dl 1.21 }
1873     }
1874    
1875     /**
1876     * allowCoreThreadTimeOut(false) causes idle threads not to time out
1877     */
1878 jsr166 1.37 public void testAllowCoreThreadTimeOut_false() throws Exception {
1879 jsr166 1.57 long keepAliveTime = timeoutMillis();
1880 jsr166 1.37 final ThreadPoolExecutor p =
1881     new ThreadPoolExecutor(2, 10,
1882 jsr166 1.57 keepAliveTime, MILLISECONDS,
1883 jsr166 1.37 new ArrayBlockingQueue<Runnable>(10));
1884 jsr166 1.98 try (PoolCleaner cleaner = cleaner(p)) {
1885     final CountDownLatch threadStarted = new CountDownLatch(1);
1886 jsr166 1.37 p.allowCoreThreadTimeOut(false);
1887     p.execute(new CheckedRunnable() {
1888     public void realRun() throws InterruptedException {
1889     threadStarted.countDown();
1890     assertTrue(p.getPoolSize() >= 1);
1891     }});
1892 jsr166 1.57 delay(2 * keepAliveTime);
1893 jsr166 1.37 assertTrue(p.getPoolSize() >= 1);
1894 dl 1.21 }
1895     }
1896    
1897 dl 1.23 /**
1898     * execute allows the same task to be submitted multiple times, even
1899     * if rejected
1900     */
1901 jsr166 1.27 public void testRejectedRecycledTask() throws InterruptedException {
1902 dl 1.23 final int nTasks = 1000;
1903 jsr166 1.37 final CountDownLatch done = new CountDownLatch(nTasks);
1904 dl 1.23 final Runnable recycledTask = new Runnable() {
1905 jsr166 1.37 public void run() {
1906     done.countDown();
1907     }};
1908 jsr166 1.24 final ThreadPoolExecutor p =
1909 jsr166 1.55 new ThreadPoolExecutor(1, 30,
1910     60, SECONDS,
1911 dl 1.127 new ArrayBlockingQueue<Runnable>(30));
1912 jsr166 1.98 try (PoolCleaner cleaner = cleaner(p)) {
1913 dl 1.23 for (int i = 0; i < nTasks; ++i) {
1914     for (;;) {
1915     try {
1916     p.execute(recycledTask);
1917     break;
1918     }
1919 jsr166 1.37 catch (RejectedExecutionException ignore) {}
1920 dl 1.23 }
1921     }
1922 jsr166 1.37 // enough time to run all tasks
1923 jsr166 1.117 await(done, nTasks * SHORT_DELAY_MS);
1924 dl 1.23 }
1925     }
1926 jsr166 1.24
1927 jsr166 1.64 /**
1928     * get(cancelled task) throws CancellationException
1929     */
1930     public void testGet_cancelled() throws Exception {
1931 jsr166 1.109 final CountDownLatch done = new CountDownLatch(1);
1932 jsr166 1.64 final ExecutorService e =
1933     new ThreadPoolExecutor(1, 1,
1934     LONG_DELAY_MS, MILLISECONDS,
1935     new LinkedBlockingQueue<Runnable>());
1936 jsr166 1.109 try (PoolCleaner cleaner = cleaner(e, done)) {
1937 jsr166 1.64 final CountDownLatch blockerStarted = new CountDownLatch(1);
1938     final List<Future<?>> futures = new ArrayList<>();
1939     for (int i = 0; i < 2; i++) {
1940     Runnable r = new CheckedRunnable() { public void realRun()
1941     throws Throwable {
1942     blockerStarted.countDown();
1943     assertTrue(done.await(2 * LONG_DELAY_MS, MILLISECONDS));
1944     }};
1945     futures.add(e.submit(r));
1946     }
1947 jsr166 1.108 await(blockerStarted);
1948 jsr166 1.64 for (Future<?> future : futures) future.cancel(false);
1949     for (Future<?> future : futures) {
1950     try {
1951     future.get();
1952     shouldThrow();
1953     } catch (CancellationException success) {}
1954     try {
1955     future.get(LONG_DELAY_MS, MILLISECONDS);
1956     shouldThrow();
1957     } catch (CancellationException success) {}
1958     assertTrue(future.isCancelled());
1959     assertTrue(future.isDone());
1960     }
1961     }
1962     }
1963    
1964 jsr166 1.122 /** Directly test simple ThreadPoolExecutor RejectedExecutionHandlers. */
1965     public void testStandardRejectedExecutionHandlers() {
1966 jsr166 1.120 final ThreadPoolExecutor p =
1967 jsr166 1.122 new ThreadPoolExecutor(1, 1, 1, SECONDS,
1968     new ArrayBlockingQueue<Runnable>(1));
1969     final AtomicReference<Thread> thread = new AtomicReference<>();
1970     final Runnable r = new Runnable() { public void run() {
1971     thread.set(Thread.currentThread()); }};
1972    
1973 jsr166 1.120 try {
1974 jsr166 1.122 new AbortPolicy().rejectedExecution(r, p);
1975 jsr166 1.120 shouldThrow();
1976     } catch (RejectedExecutionException success) {}
1977 jsr166 1.122 assertNull(thread.get());
1978    
1979     new DiscardPolicy().rejectedExecution(r, p);
1980     assertNull(thread.get());
1981 jsr166 1.120
1982 jsr166 1.122 new CallerRunsPolicy().rejectedExecution(r, p);
1983 jsr166 1.121 assertSame(Thread.currentThread(), thread.get());
1984 jsr166 1.122
1985     // check that pool was not perturbed by handlers
1986 jsr166 1.121 assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy);
1987     assertEquals(0, p.getTaskCount());
1988     assertTrue(p.getQueue().isEmpty());
1989     }
1990    
1991 jsr166 1.125 public void testThreadFactoryReturnsTerminatedThread_shouldThrow() {
1992     if (!testImplementationDetails)
1993     return;
1994    
1995     ThreadFactory returnsTerminatedThread = runnableIgnored -> {
1996     Thread thread = new Thread(() -> {});
1997     thread.start();
1998     try { thread.join(); }
1999     catch (InterruptedException ex) { throw new Error(ex); }
2000     return thread;
2001     };
2002     ThreadPoolExecutor p =
2003     new ThreadPoolExecutor(1, 1, 1, SECONDS,
2004     new ArrayBlockingQueue<Runnable>(1),
2005     returnsTerminatedThread);
2006     try (PoolCleaner cleaner = cleaner(p)) {
2007     assertThrows(IllegalThreadStateException.class,
2008     () -> p.execute(() -> {}));
2009     }
2010     }
2011    
2012     public void testThreadFactoryReturnsStartedThread_shouldThrow() {
2013     if (!testImplementationDetails)
2014     return;
2015    
2016     CountDownLatch latch = new CountDownLatch(1);
2017     Runnable awaitLatch = () -> {
2018     try { latch.await(); }
2019     catch (InterruptedException ex) { throw new Error(ex); }};
2020     ThreadFactory returnsStartedThread = runnable -> {
2021     Thread thread = new Thread(awaitLatch);
2022     thread.start();
2023     return thread;
2024     };
2025     ThreadPoolExecutor p =
2026     new ThreadPoolExecutor(1, 1, 1, SECONDS,
2027     new ArrayBlockingQueue<Runnable>(1),
2028     returnsStartedThread);
2029     try (PoolCleaner cleaner = cleaner(p)) {
2030     assertThrows(IllegalThreadStateException.class,
2031     () -> p.execute(() -> {}));
2032     latch.countDown();
2033     }
2034     }
2035    
2036 dl 1.1 }