Skip to content

Commit

Permalink
add test to ListenableFutureUtils#toCompletableFuture
Browse files Browse the repository at this point in the history
case: interrupt thread
  • Loading branch information
linzee1 committed Jul 28, 2024
1 parent 822bf45 commit 0ccab8f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class ListenableFutureUtils {
* Cancelling the result {@link CompletableFuture} will also cancel inner {@link ListenableFuture}.
* Use param {@code mayInterruptIfRunning} to control whether to interrupt the thread of {@link ListenableFuture}.
* <p>
* Note: CompletionException caused by this CancellationException is also considered cancellation.
* Note: CompletionException caused by CancellationException is also considered cancellation.
* <p>
* We encourage you to avoid using direct write methods in {@link CompletableFuture} so that the underlying
* {@link ListenableFuture} can benefit from cancel propagation.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.JRE;

import java.time.Duration;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

import static io.foldright.cffu.ListenableFutureUtils.*;
import static io.foldright.test_utils.TestUtils.*;
Expand Down Expand Up @@ -129,6 +131,30 @@ void test_lf2cf_setCancellationExceptionToCf_cancellationAndPropagation() throws
assertThrowsExactly(CancellationException.class, cf::get);
}

@Test
void test_lf2cf_setCancellationExceptionToCf_cancellationAndPropagation_interruption() throws Exception {
final AtomicBoolean interrupted = new AtomicBoolean(false);
final ListenableFuture<Integer> lf = Futures.submit(() -> {
try {
Thread.sleep(Duration.ofSeconds(10));
} catch (InterruptedException ex) {
interrupted.set(true);
}
return 42;
}, Executors.newCachedThreadPool());
final CompletableFuture<Integer> cf = toCompletableFuture(lf, executorService, true);

assertTrue(cf.completeExceptionally(new CancellationException()));
waitForAllCfsToComplete(cf);
waitForAllLfsToComplete(lf);

assertTrue(lf.isCancelled());
assertThrowsExactly(CancellationException.class, lf::get);
assertTrue(cf.isCancelled());
assertThrowsExactly(CancellationException.class, cf::get);
assertTrue(interrupted.get());
}

@Test
void test_cf2lf_cancellationAndPropagation() throws Exception {
final CompletableFuture<Integer> cf = new CompletableFuture<>();
Expand Down

0 comments on commit 0ccab8f

Please sign in to comment.