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