|
17 | 17 |
|
18 | 18 | package org.apache.commons.lang3.concurrent; |
19 | 19 |
|
20 | | -import static org.junit.jupiter.api.Assertions.assertEquals; |
21 | | -import static org.junit.jupiter.api.Assertions.assertThrows; |
22 | | - |
23 | 20 | import java.util.Arrays; |
24 | 21 | import java.util.List; |
25 | | -import java.util.concurrent.ExecutionException; |
26 | | -import java.util.concurrent.Future; |
27 | | -import java.util.concurrent.TimeUnit; |
28 | | -import java.util.concurrent.TimeoutException; |
| 22 | +import java.util.concurrent.*; |
| 23 | +import java.util.function.Consumer; |
29 | 24 | import java.util.stream.Collectors; |
30 | 25 |
|
31 | 26 | import org.apache.commons.lang3.AbstractLangTest; |
32 | 27 | import org.apache.commons.lang3.exception.UncheckedInterruptedException; |
| 28 | +import org.junit.jupiter.api.RepeatedTest; |
33 | 29 | import org.junit.jupiter.api.Test; |
34 | 30 |
|
| 31 | +import static org.junit.jupiter.api.Assertions.*; |
| 32 | + |
35 | 33 | /** |
36 | 34 | * Tests {@link UncheckedFuture}. |
37 | 35 | */ |
@@ -121,4 +119,44 @@ void testOnFuture() { |
121 | 119 | assertEquals("Z", UncheckedFuture.on(new TestFuture<>("Z")).get()); |
122 | 120 | } |
123 | 121 |
|
| 122 | + @RepeatedTest(10) |
| 123 | + void interruptFlagIsPreservedOnGet() throws Exception { |
| 124 | + assertInterruptPreserved(future -> future.get()); |
| 125 | + } |
| 126 | + |
| 127 | + @RepeatedTest(10) |
| 128 | + void interruptFlagIsPreservedOnGetWithTimeout() throws Exception { |
| 129 | + assertInterruptPreserved(future -> future.get(2, TimeUnit.SECONDS)); |
| 130 | + } |
| 131 | + |
| 132 | + private static void assertInterruptPreserved( |
| 133 | + Consumer<UncheckedFuture<Integer>> futureCall) throws Exception { |
| 134 | + |
| 135 | + ExecutorService executor = Executors.newFixedThreadPool(2); |
| 136 | + try { |
| 137 | + CountDownLatch future2IsAboutToWait = new CountDownLatch(1); |
| 138 | + Future<Integer> future1 = executor.submit(() -> { |
| 139 | + Thread.sleep(10_000); |
| 140 | + return 42; |
| 141 | + }); |
| 142 | + Future<Integer> future2 = executor.submit(() -> { |
| 143 | + future2IsAboutToWait.countDown(); |
| 144 | + try { |
| 145 | + futureCall.accept(UncheckedFuture.on(future1)); |
| 146 | + return 1; |
| 147 | + } catch (RuntimeException e) { |
| 148 | + assertTrue(Thread.currentThread().isInterrupted()); |
| 149 | + return 2; |
| 150 | + } |
| 151 | + }); |
| 152 | + |
| 153 | + assertTrue(future2IsAboutToWait.await(2, TimeUnit.SECONDS)); |
| 154 | + executor.shutdownNow(); |
| 155 | + assertEquals(2, future2.get(2, TimeUnit.SECONDS)); |
| 156 | + } finally { |
| 157 | + executor.shutdownNow(); |
| 158 | + executor.awaitTermination(10, TimeUnit.SECONDS); |
| 159 | + } |
| 160 | + } |
| 161 | + |
124 | 162 | } |
0 commit comments