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

File Contents

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