1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
|
/*
* Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test id=platform
* @summary Basic tests for new thread-per-task executors
* @run junit/othervm -DthreadFactory=platform ThreadPerTaskExecutorTest
*/
/*
* @test id=virtual
* @run junit/othervm -DthreadFactory=virtual ThreadPerTaskExecutorTest
*/
import java.time.Duration;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.lang.Thread.State.*;
import static java.util.concurrent.Future.State.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.*;
class ThreadPerTaskExecutorTest {
private static ScheduledExecutorService scheduler;
private static List<ThreadFactory> threadFactories;
@BeforeAll
static void setup() throws Exception {
scheduler = Executors.newSingleThreadScheduledExecutor();
// thread factories
String value = System.getProperty("threadFactory");
List<ThreadFactory> list = new ArrayList<>();
if (value == null || value.equals("platform"))
list.add(Thread.ofPlatform().factory());
if (value == null || value.equals("virtual"))
list.add(Thread.ofVirtual().factory());
assertTrue(list.size() > 0, "No thread factories for tests");
threadFactories = list;
}
@AfterAll
static void shutdown() {
scheduler.shutdown();
}
private static Stream<ThreadFactory> factories() {
return threadFactories.stream();
}
private static Stream<ExecutorService> executors() {
return threadFactories.stream()
.map(f -> Executors.newThreadPerTaskExecutor(f));
}
/**
* Test that a thread is created for each task.
*/
@ParameterizedTest
@MethodSource("factories")
void testThreadPerTask(ThreadFactory factory) throws Exception {
final int NUM_TASKS = 100;
AtomicInteger threadCount = new AtomicInteger();
ThreadFactory wrapper = task -> {
threadCount.addAndGet(1);
return factory.newThread(task);
};
var futures = new ArrayList<Future<Integer>>();
ExecutorService executor = Executors.newThreadPerTaskExecutor(wrapper);
try (executor) {
for (int i=0; i<NUM_TASKS; i++) {
int result = i;
Future<Integer> future = executor.submit(() -> result);
futures.add(future);
}
}
assertTrue(executor.isTerminated());
assertEquals(NUM_TASKS, threadCount.get());
for (int i=0; i<NUM_TASKS; i++) {
Future<Integer> future = futures.get(i);
assertEquals((int) future.get(), i);
}
}
/**
* Test that newThreadPerTaskExecutor uses the specified thread factory.
*/
@Test
void testThreadFactory() throws Exception {
var ref1 = new AtomicReference<Thread>();
var ref2 = new AtomicReference<Thread>();
ThreadFactory factory = task -> {
assertTrue(ref1.get() == null);
Thread thread = new Thread(task);
ref1.set(thread);
return thread;
};
try (var executor = Executors.newThreadPerTaskExecutor(factory)) {
executor.submit(() -> ref2.set(Thread.currentThread()));
}
Thread thread1 = ref1.get(); // Thread created by thread factory
Thread thread2 = ref2.get(); // Thread that executed task
assertTrue(thread1 == thread2);
}
/**
* Test shutdown.
*/
@ParameterizedTest
@MethodSource("executors")
void testShutdown(ExecutorService executor) throws Exception {
try (executor) {
assertFalse(executor.isShutdown());
assertFalse(executor.isTerminated());
assertFalse(executor.awaitTermination(10, TimeUnit.MILLISECONDS));
Future<Void> future = executor.submit(new LongRunningTask<Void>());
try {
executor.shutdown();
assertTrue(executor.isShutdown());
assertFalse(executor.isTerminated());
assertFalse(executor.awaitTermination(500, TimeUnit.MILLISECONDS));
} finally {
future.cancel(true); // interrupt task
}
}
}
/**
* Test shutdownNow.
*/
@ParameterizedTest
@MethodSource("executors")
void testShutdownNow(ExecutorService executor) throws Exception {
try (executor) {
assertFalse(executor.isShutdown());
assertFalse(executor.isTerminated());
assertFalse(executor.awaitTermination(10, TimeUnit.MILLISECONDS));
var task = new LongRunningTask<Void>();
Future<Void> future = executor.submit(task);
try {
task.awaitStarted();
List<Runnable> tasks = executor.shutdownNow();
assertTrue(executor.isShutdown());
assertTrue(tasks.isEmpty());
Throwable e = assertThrows(ExecutionException.class, future::get);
assertTrue(e.getCause() instanceof InterruptedException);
assertTrue(executor.awaitTermination(3, TimeUnit.SECONDS));
assertTrue(executor.isTerminated());
} finally {
future.cancel(true);
}
}
}
/**
* Test close with no threads running.
*/
@ParameterizedTest
@MethodSource("executors")
void testClose1(ExecutorService executor) throws Exception {
executor.close();
assertTrue(executor.isShutdown());
assertTrue(executor.isTerminated());
assertTrue(executor.awaitTermination(10, TimeUnit.MILLISECONDS));
}
/**
* Test close with threads running.
*/
@ParameterizedTest
@MethodSource("executors")
void testClose2(ExecutorService executor) throws Exception {
Future<String> future;
try (executor) {
future = executor.submit(() -> {
Thread.sleep(Duration.ofMillis(50));
return "foo";
});
}
assertTrue(executor.isShutdown());
assertTrue(executor.isTerminated());
assertTrue(executor.awaitTermination(10, TimeUnit.MILLISECONDS));
assertEquals(future.get(), "foo"); // task should complete
}
/**
* Invoke close with interrupt status set.
*/
@ParameterizedTest
@MethodSource("executors")
void testClose3(ExecutorService executor) throws Exception {
Future<Void> future;
try (executor) {
var task = new LongRunningTask<Void>();
future = executor.submit(task);
task.awaitStarted();
Thread.currentThread().interrupt();
} finally {
assertTrue(Thread.interrupted()); // clear interrupt
}
assertTrue(executor.isShutdown());
assertTrue(executor.isTerminated());
assertTrue(executor.awaitTermination(10, TimeUnit.MILLISECONDS));
Throwable e = assertThrows(ExecutionException.class, future::get);
assertTrue(e.getCause() instanceof InterruptedException);
}
/**
* Interrupt thread blocked in close.
*/
@ParameterizedTest
@MethodSource("executors")
void testClose4(ExecutorService executor) throws Exception {
Future<Void> future;
try (executor) {
var task = new LongRunningTask<Void>();
future = executor.submit(task);
task.awaitStarted();
scheduleInterruptAt("java.util.concurrent.ThreadPerTaskExecutor.close");
} finally {
assertTrue(Thread.interrupted());
}
assertTrue(executor.isShutdown());
assertTrue(executor.isTerminated());
assertTrue(executor.awaitTermination(10, TimeUnit.MILLISECONDS));
Throwable e = assertThrows(ExecutionException.class, future::get);
assertTrue(e.getCause() instanceof InterruptedException);
}
/**
* Close executor that is already closed.
*/
@ParameterizedTest
@MethodSource("executors")
void testClose5(ExecutorService executor) throws Exception {
executor.close();
executor.close(); // already closed
}
/**
* Test awaitTermination when not shutdown.
*/
@ParameterizedTest
@MethodSource("executors")
void testAwaitTermination1(ExecutorService executor) throws Exception {
assertFalse(executor.awaitTermination(100, TimeUnit.MILLISECONDS));
executor.close();
assertTrue(executor.awaitTermination(100, TimeUnit.MILLISECONDS));
}
/**
* Test awaitTermination with task running.
*/
@ParameterizedTest
@MethodSource("executors")
void testAwaitTermination2(ExecutorService executor) throws Exception {
Phaser barrier = new Phaser(2);
Future<?> future = executor.submit(barrier::arriveAndAwaitAdvance);
try {
executor.shutdown();
assertFalse(executor.awaitTermination(100, TimeUnit.MILLISECONDS));
barrier.arriveAndAwaitAdvance();
assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
} finally {
future.cancel(true);
}
}
/**
* Test submit when the Executor is shutdown but not terminated.
*/
@ParameterizedTest
@MethodSource("executors")
void testSubmitAfterShutdown(ExecutorService executor) throws Exception {
Phaser barrier = new Phaser(2);
try (executor) {
// submit task to prevent executor from terminating
executor.submit(barrier::arriveAndAwaitAdvance);
try {
executor.shutdown();
assertTrue(executor.isShutdown() && !executor.isTerminated());
assertThrows(RejectedExecutionException.class,
() -> executor.submit(() -> { }));
} finally {
barrier.arriveAndAwaitAdvance();
}
}
}
/**
* Test submit when the Executor is terminated.
*/
@ParameterizedTest
@MethodSource("executors")
void testSubmitAfterTermination(ExecutorService executor) throws Exception {
executor.shutdown();
assertTrue(executor.isShutdown() && executor.isTerminated());
assertThrows(RejectedExecutionException.class, () -> executor.submit(() -> {}));
}
/**
* Test submit with null.
*/
@ParameterizedTest
@MethodSource("factories")
void testSubmitNulls1(ThreadFactory factory) {
var executor = Executors.newThreadPerTaskExecutor(factory);
assertThrows(NullPointerException.class, () -> executor.submit((Runnable) null));
}
@ParameterizedTest
@MethodSource("factories")
void testSubmitNulls2(ThreadFactory factory) {
var executor = Executors.newThreadPerTaskExecutor(factory);
assertThrows(NullPointerException.class, () -> executor.submit((Callable<String>) null));
}
/**
* Test invokeAny where all tasks complete normally.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAny1(ExecutorService executor) throws Exception {
try (executor) {
Callable<String> task1 = () -> "foo";
Callable<String> task2 = () -> "bar";
String result = executor.invokeAny(Set.of(task1, task2));
assertTrue("foo".equals(result) || "bar".equals(result));
}
}
/**
* Test invokeAny where all tasks complete normally. The completion of the
* first task should cancel remaining tasks.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAny2(ExecutorService executor) throws Exception {
try (executor) {
Callable<String> task1 = () -> "foo";
var task2 = new LongRunningTask<String>();
String result = executor.invokeAny(Set.of(task1, task2));
assertTrue("foo".equals(result));
// if task2 started then it should be interrupted
if (task2.isStarted()) {
task2.awaitDone();
assertTrue(task2.isInterrupted());
}
}
}
/**
* Test invokeAny where all tasks complete with exception.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAny3(ExecutorService executor) throws Exception {
try (executor) {
class FooException extends Exception { }
Callable<String> task1 = () -> { throw new FooException(); };
Callable<String> task2 = () -> { throw new FooException(); };
try {
executor.invokeAny(Set.of(task1, task2));
fail("invokeAny did not throw");
} catch (ExecutionException e) {
Throwable cause = e.getCause();
assertTrue(cause instanceof FooException);
}
}
}
/**
* Test invokeAny where all tasks complete with exception. The completion
* of the last task is delayed.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAny4(ExecutorService executor) throws Exception {
try (executor) {
class FooException extends Exception { }
Callable<String> task1 = () -> { throw new FooException(); };
Callable<String> task2 = () -> {
Thread.sleep(Duration.ofMillis(50));
throw new FooException();
};
try {
executor.invokeAny(Set.of(task1, task2));
fail("invokeAny did not throw");
} catch (ExecutionException e) {
Throwable cause = e.getCause();
assertTrue(cause instanceof FooException);
}
}
}
/**
* Test invokeAny where some, not all, tasks complete normally.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAny5(ExecutorService executor) throws Exception {
try (executor) {
class FooException extends Exception { }
Callable<String> task1 = () -> "foo";
Callable<String> task2 = () -> { throw new FooException(); };
String result = executor.invokeAny(Set.of(task1, task2));
assertTrue("foo".equals(result));
}
}
/**
* Test invokeAny where some, not all, tasks complete normally. The
* completion of the first task to complete normally is delayed.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAny6(ExecutorService executor) throws Exception {
try (executor) {
class FooException extends Exception { }
Callable<String> task1 = () -> {
Thread.sleep(Duration.ofMillis(50));
return "foo";
};
Callable<String> task2 = () -> { throw new FooException(); };
String result = executor.invokeAny(Set.of(task1, task2));
assertTrue("foo".equals(result));
}
}
/**
* Test timed-invokeAny where all tasks complete normally before the timeout.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAnyWithTimeout1(ExecutorService executor) throws Exception {
try (executor) {
Callable<String> task1 = () -> "foo";
Callable<String> task2 = () -> "bar";
String result = executor.invokeAny(Set.of(task1, task2), 1, TimeUnit.MINUTES);
assertTrue("foo".equals(result) || "bar".equals(result));
}
}
/**
* Test timed-invokeAny where one task completes normally before the timeout.
* The remaining tests should be cancelled.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAnyWithTimeout2(ExecutorService executor) throws Exception {
try (executor) {
Callable<String> task1 = () -> "foo";
var task2 = new LongRunningTask<String>();
String result = executor.invokeAny(Set.of(task1, task2), 1, TimeUnit.MINUTES);
assertTrue("foo".equals(result));
// if task2 started then it should be interrupted
if (task2.isStarted()) {
task2.awaitDone();
assertTrue(task2.isInterrupted());
}
}
}
/**
* Test timed-invokeAny where timeout expires before any task completes.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAnyWithTimeout3(ExecutorService executor) throws Exception {
try (executor) {
Callable<String> task1 = () -> {
Thread.sleep(Duration.ofMinutes(1));
return "foo";
};
Callable<String> task2 = () -> {
Thread.sleep(Duration.ofMinutes(2));
return "bar";
};
assertThrows(TimeoutException.class,
() -> executor.invokeAny(Set.of(task1, task2), 1, TimeUnit.SECONDS));
}
}
/**
* Test invokeAny where timeout expires after some tasks have completed
* with exception.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAnyWithTimeout4(ExecutorService executor) throws Exception {
try (executor) {
class FooException extends Exception { }
Callable<String> task1 = () -> { throw new FooException(); };
Callable<String> task2 = () -> {
Thread.sleep(Duration.ofMinutes(2));
return "bar";
};
assertThrows(TimeoutException.class,
() -> executor.invokeAny(Set.of(task1, task2), 1, TimeUnit.SECONDS));
}
}
/**
* Test invokeAny with interrupt status set.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAnyWithInterruptSet(ExecutorService executor) throws Exception {
try (executor) {
Callable<String> task1 = () -> "foo";
Callable<String> task2 = () -> "bar";
Thread.currentThread().interrupt();
try {
executor.invokeAny(Set.of(task1, task2));
fail("invokeAny did not throw");
} catch (InterruptedException expected) {
assertFalse(Thread.currentThread().isInterrupted());
} finally {
Thread.interrupted(); // clear interrupt
}
}
}
/**
* Test interrupting a thread blocked in invokeAny.
*/
@ParameterizedTest
@MethodSource("executors")
void testInterruptInvokeAny(ExecutorService executor) throws Exception {
try (executor) {
var task = new LongRunningTask<Void>();
try {
scheduleInterruptAt("java.util.concurrent.ThreadPerTaskExecutor.invokeAny");
executor.invokeAny(Set.of(task));
fail("invokeAny did not throw");
} catch (InterruptedException expected) {
assertFalse(Thread.currentThread().isInterrupted());
// if task started then it should be interrupted
if (task.isStarted()) {
task.awaitDone();
assertTrue(task.isInterrupted());
}
} finally {
Thread.interrupted(); // clear interrupt
}
}
}
/**
* Test invokeAny after ExecutorService has been shutdown.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAnyAfterShutdown(ExecutorService executor) throws Exception {
executor.shutdown();
Callable<String> task1 = () -> "foo";
Callable<String> task2 = () -> "bar";
assertThrows(RejectedExecutionException.class,
() -> executor.invokeAny(Set.of(task1, task2)));
}
/**
* Test invokeAny with empty collection.
*/
@ParameterizedTest
@MethodSource("factories")
void testInvokeAnyEmpty1(ThreadFactory factory) throws Exception {
try (var executor = Executors.newThreadPerTaskExecutor(factory)) {
assertThrows(IllegalArgumentException.class, () -> executor.invokeAny(Set.of()));
}
}
/**
* Test timed-invokeAny with empty collection.
*/
@ParameterizedTest
@MethodSource("factories")
void testInvokeAnyEmpty2(ThreadFactory factory) throws Exception {
try (var executor = Executors.newThreadPerTaskExecutor(factory)) {
assertThrows(IllegalArgumentException.class,
() -> executor.invokeAny(Set.of(), 1, TimeUnit.MINUTES));
}
}
/**
* Test invokeAny with null.
*/
@ParameterizedTest
@MethodSource("factories")
void testInvokeAnyNull1(ThreadFactory factory) throws Exception {
try (var executor = Executors.newThreadPerTaskExecutor(factory)) {
assertThrows(NullPointerException.class, () -> executor.invokeAny(null));
}
}
/**
* Test invokeAny with null element
*/
@ParameterizedTest
@MethodSource("factories")
void testInvokeAnyNull2(ThreadFactory factory) throws Exception {
try (var executor = Executors.newThreadPerTaskExecutor(factory)) {
List<Callable<String>> list = new ArrayList<>();
list.add(() -> "foo");
list.add(null);
assertThrows(NullPointerException.class, () -> executor.invokeAny(null));
}
}
/**
* Test invokeAll where all tasks complete normally.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAll1(ExecutorService executor) throws Exception {
try (executor) {
Callable<String> task1 = () -> "foo";
Callable<String> task2 = () -> {
Thread.sleep(Duration.ofMillis(50));
return "bar";
};
List<Future<String>> list = executor.invokeAll(List.of(task1, task2));
// list should have two elements, both should be done
assertTrue(list.size() == 2);
boolean notDone = list.stream().anyMatch(r -> !r.isDone());
assertFalse(notDone);
// check results
List<String> results = list.stream().map(Future::resultNow).collect(Collectors.toList());
assertEquals(results, List.of("foo", "bar"));
}
}
/**
* Test invokeAll where all tasks complete with exception.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAll2(ExecutorService executor) throws Exception {
try (executor) {
class FooException extends Exception { }
class BarException extends Exception { }
Callable<String> task1 = () -> { throw new FooException(); };
Callable<String> task2 = () -> {
Thread.sleep(Duration.ofMillis(50));
throw new BarException();
};
List<Future<String>> list = executor.invokeAll(List.of(task1, task2));
// list should have two elements, both should be done
assertTrue(list.size() == 2);
boolean notDone = list.stream().anyMatch(r -> !r.isDone());
assertFalse(notDone);
// check results
Throwable e1 = assertThrows(ExecutionException.class, () -> list.get(0).get());
assertTrue(e1.getCause() instanceof FooException);
Throwable e2 = assertThrows(ExecutionException.class, () -> list.get(1).get());
assertTrue(e2.getCause() instanceof BarException);
}
}
/**
* Test invokeAll where all tasks complete normally before the timeout expires.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAll3(ExecutorService executor) throws Exception {
try (executor) {
Callable<String> task1 = () -> "foo";
Callable<String> task2 = () -> {
Thread.sleep(Duration.ofMillis(50));
return "bar";
};
List<Future<String>> list = executor.invokeAll(List.of(task1, task2), 1, TimeUnit.DAYS);
// list should have two elements, both should be done
assertTrue(list.size() == 2);
boolean notDone = list.stream().anyMatch(r -> !r.isDone());
assertFalse(notDone);
// check results
List<String> results = list.stream().map(Future::resultNow).collect(Collectors.toList());
assertEquals(results, List.of("foo", "bar"));
}
}
/**
* Test invokeAll where some tasks do not complete before the timeout expires.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAll4(ExecutorService executor) throws Exception {
try (executor) {
AtomicReference<Exception> exc = new AtomicReference<>();
Callable<String> task1 = () -> "foo";
Callable<String> task2 = () -> {
try {
Thread.sleep(Duration.ofDays(1));
return "bar";
} catch (Exception e) {
exc.set(e);
throw e;
}
};
var list = executor.invokeAll(List.of(task1, task2), 2, TimeUnit.SECONDS);
// list should have two elements, both should be done
assertTrue(list.size() == 2);
boolean notDone = list.stream().anyMatch(r -> !r.isDone());
assertFalse(notDone);
// check results
assertEquals(list.get(0).get(), "foo");
assertTrue(list.get(1).isCancelled());
// task2 should be interrupted
Exception e;
while ((e = exc.get()) == null) {
Thread.sleep(50);
}
assertTrue(e instanceof InterruptedException);
}
}
/**
* Test untimed-invokeAll with interrupt status set.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAllInterrupt1(ExecutorService executor) throws Exception {
try (executor) {
Callable<String> task1 = () -> "foo";
Callable<String> task2 = () -> {
Thread.sleep(Duration.ofMinutes(1));
return "bar";
};
Thread.currentThread().interrupt();
try {
executor.invokeAll(List.of(task1, task2));
fail("invokeAll did not throw");
} catch (InterruptedException expected) {
assertFalse(Thread.currentThread().isInterrupted());
} finally {
Thread.interrupted(); // clear interrupt
}
}
}
/**
* Test timed-invokeAll with interrupt status set.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAllInterrupt3(ExecutorService executor) throws Exception {
try (executor) {
Callable<String> task1 = () -> "foo";
Callable<String> task2 = () -> {
Thread.sleep(Duration.ofMinutes(1));
return "bar";
};
Thread.currentThread().interrupt();
try {
executor.invokeAll(List.of(task1, task2), 1, TimeUnit.SECONDS);
fail("invokeAll did not throw");
} catch (InterruptedException expected) {
assertFalse(Thread.currentThread().isInterrupted());
} finally {
Thread.interrupted(); // clear interrupt
}
}
}
/**
* Test interrupt of thread blocked in untimed-invokeAll.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAllInterrupt4(ExecutorService executor) throws Exception {
try (executor) {
var task = new LongRunningTask<Void>();
try {
scheduleInterruptAt("java.util.concurrent.ThreadPerTaskExecutor.invokeAll");
executor.invokeAll(Set.of(task));
fail("invokeAll did not throw");
} catch (InterruptedException expected) {
assertFalse(Thread.currentThread().isInterrupted());
// if task started then it should be interrupted
if (task.isStarted()) {
task.awaitDone();
assertTrue(task.isInterrupted());
}
} finally {
Thread.interrupted(); // clear interrupt
}
}
}
/**
* Test interrupt of thread blocked in timed-invokeAll.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAllInterrupt5(ExecutorService executor) throws Exception {
try (executor) {
var task = new LongRunningTask<Void>();
try {
scheduleInterruptAt("java.util.concurrent.ThreadPerTaskExecutor.invokeAll");
executor.invokeAll(Set.of(task), 1, TimeUnit.DAYS);
fail("invokeAll did not throw");
} catch (InterruptedException expected) {
assertFalse(Thread.currentThread().isInterrupted());
// if task started then it should be interrupted
if (task.isStarted()) {
task.awaitDone();
assertTrue(task.isInterrupted());
}
} finally {
Thread.interrupted(); // clear interrupt
}
}
}
/**
* Test invokeAll after ExecutorService has been shutdown.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAllAfterShutdown1(ExecutorService executor) throws Exception {
executor.shutdown();
Callable<String> task1 = () -> "foo";
Callable<String> task2 = () -> "bar";
assertThrows(RejectedExecutionException.class,
() -> executor.invokeAll(Set.of(task1, task2)));
}
@ParameterizedTest
@MethodSource("executors")
void testInvokeAllAfterShutdown2(ExecutorService executor) throws Exception {
executor.shutdown();
Callable<String> task1 = () -> "foo";
Callable<String> task2 = () -> "bar";
assertThrows(RejectedExecutionException.class,
() -> executor.invokeAll(Set.of(task1, task2), 1, TimeUnit.SECONDS));
}
/**
* Test invokeAll with empty collection.
*/
@ParameterizedTest
@MethodSource("executors")
void testInvokeAllEmpty1(ExecutorService executor) throws Exception {
try (executor) {
List<Future<Object>> list = executor.invokeAll(Set.of());
assertTrue(list.size() == 0);
}
}
@ParameterizedTest
@MethodSource("executors")
void testInvokeAllEmpty2(ExecutorService executor) throws Exception {
try (executor) {
List<Future<Object>> list = executor.invokeAll(Set.of(), 1, TimeUnit.SECONDS);
assertTrue(list.size() == 0);
}
}
@ParameterizedTest
@MethodSource("factories")
void testInvokeAllNull1(ThreadFactory factory) throws Exception {
try (var executor = Executors.newThreadPerTaskExecutor(factory)) {
assertThrows(NullPointerException.class, () -> executor.invokeAll(null));
}
}
@ParameterizedTest
@MethodSource("factories")
void testInvokeAllNull2(ThreadFactory factory) throws Exception {
try (var executor = Executors.newThreadPerTaskExecutor(factory)) {
List<Callable<String>> tasks = new ArrayList<>();
tasks.add(() -> "foo");
tasks.add(null);
assertThrows(NullPointerException.class, () -> executor.invokeAll(tasks));
}
}
@ParameterizedTest
@MethodSource("factories")
void testInvokeAllNull3(ThreadFactory factory) throws Exception {
try (var executor = Executors.newThreadPerTaskExecutor(factory)) {
assertThrows(NullPointerException.class,
() -> executor.invokeAll(null, 1, TimeUnit.SECONDS));
}
}
@ParameterizedTest
@MethodSource("factories")
void testInvokeAllNull4(ThreadFactory factory) throws Exception {
try (var executor = Executors.newThreadPerTaskExecutor(factory)) {
Callable<String> task = () -> "foo";
assertThrows(NullPointerException.class,
() -> executor.invokeAll(List.of(task), 1, null));
}
}
@ParameterizedTest
@MethodSource("factories")
void testInvokeAllNull5(ThreadFactory factory) throws Exception {
try (var executor = Executors.newThreadPerTaskExecutor(factory)) {
List<Callable<String>> tasks = new ArrayList<>();
tasks.add(() -> "foo");
tasks.add(null);
assertThrows(NullPointerException.class,
() -> executor.invokeAll(tasks, 1, TimeUnit.SECONDS));
}
}
/**
* Test ThreadFactory that does not produce any threads
*/
@Test
void testNoThreads1() throws Exception {
ExecutorService executor = Executors.newThreadPerTaskExecutor(task -> null);
assertThrows(RejectedExecutionException.class, () -> executor.execute(() -> { }));
}
@Test
void testNoThreads2() throws Exception {
ExecutorService executor = Executors.newThreadPerTaskExecutor(task -> null);
assertThrows(RejectedExecutionException.class, () -> executor.submit(() -> "foo"));
}
@Test
void testNoThreads3() throws Exception {
ExecutorService executor = Executors.newThreadPerTaskExecutor(task -> null);
assertThrows(RejectedExecutionException.class,
() -> executor.invokeAll(List.of(() -> "foo")));
}
@Test
void testNoThreads4() throws Exception {
ExecutorService executor = Executors.newThreadPerTaskExecutor(task -> null);
assertThrows(RejectedExecutionException.class,
() -> executor.invokeAny(List.of(() -> "foo")));
}
@Test
void testNull() {
assertThrows(NullPointerException.class,
() -> Executors.newThreadPerTaskExecutor(null));
}
/**
* Schedules the current thread to be interrupted when it waits (timed or untimed)
* at the given location "{@code c.m}" where {@code c} is the fully qualified class
* name and {@code m} is the method name.
*/
private void scheduleInterruptAt(String location) {
int index = location.lastIndexOf('.');
String className = location.substring(0, index);
String methodName = location.substring(index + 1);
Thread target = Thread.currentThread();
scheduler.submit(() -> {
try {
boolean found = false;
while (!found) {
Thread.State state = target.getState();
assertTrue(state != TERMINATED);
if ((state == WAITING || state == TIMED_WAITING)
&& contains(target.getStackTrace(), className, methodName)) {
found = true;
} else {
Thread.sleep(20);
}
}
target.interrupt();
} catch (Exception e) {
e.printStackTrace();
}
});
}
/**
* Returns true if the given stack trace contains an element for the given class
* and method name.
*/
private boolean contains(StackTraceElement[] stack, String className, String methodName) {
return Arrays.stream(stack)
.anyMatch(e -> className.equals(e.getClassName())
&& methodName.equals(e.getMethodName()));
}
/**
* Long running task with methods to test if the task has started, finished,
* and interrupted.
*/
private static class LongRunningTask<T> implements Callable<T> {
final CountDownLatch started = new CountDownLatch(1);
final CountDownLatch done = new CountDownLatch(1);
volatile boolean interrupted;
@Override
public T call() throws InterruptedException {
started.countDown();
try {
Thread.sleep(Duration.ofDays(1));
} catch (InterruptedException e) {
interrupted = true;
throw e;
} finally {
done.countDown();
}
return null;
}
/**
* Wait for the task to start execution.
*/
LongRunningTask<T> awaitStarted() throws InterruptedException {
started.await();
return this;
}
/**
* Wait for the task to finish execution.
*/
LongRunningTask<T> awaitDone() throws InterruptedException {
done.await();
return this;
}
/**
* Returns true if the task started execution.
*/
boolean isStarted() {
return started.getCount() == 0;
}
/**
* Returns true if the task was interrupted.
*/
boolean isInterrupted() {
assertTrue(done.getCount() == 0); // shouldn't call before finished
return interrupted;
}
}
}
|