Skip to content

Commit d251fea

Browse files
committed
Support external cancellation of a FailsafeFuture with ExecutionContext.isCancelled
1 parent 1574e20 commit d251fea

File tree

3 files changed

+16
-6
lines changed

3 files changed

+16
-6
lines changed

src/main/java/net/jodah/failsafe/FailsafeFuture.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
*/
3030
class FailsafeFuture<T> extends CompletableFuture<T> {
3131
private final FailsafeExecutor<T> executor;
32-
private ExecutionContext execution;
32+
private AbstractExecution execution;
3333

3434
// Mutable state, guarded by "this"
3535
private Future<T> delegate;
@@ -95,7 +95,13 @@ synchronized Future<T> getDelegate() {
9595
return delegate;
9696
}
9797

98+
/**
99+
* Cancels the delegate passing in the {@code interruptDelegate} flag, cancels all timeout delegates, and marks the
100+
* execution as cancelled.
101+
*/
98102
synchronized boolean cancelDelegates(boolean interruptDelegate, boolean result) {
103+
execution.cancelled = true;
104+
execution.interrupted = interruptDelegate;
99105
if (delegate != null)
100106
result = delegate.cancel(interruptDelegate);
101107
if (timeoutDelegates != null)
@@ -119,7 +125,7 @@ synchronized void injectTimeout(Future<T> timeoutDelegate) {
119125
timeoutDelegates.add(timeoutDelegate);
120126
}
121127

122-
void inject(ExecutionContext execution) {
128+
void inject(AbstractExecution execution) {
123129
this.execution = execution;
124130
}
125131
}

src/main/java/net/jodah/failsafe/TimeoutExecutor.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,8 +115,6 @@ protected Supplier<CompletableFuture<ExecutionResult>> supplyAsync(
115115
boolean canInterrupt = policy.canInterrupt();
116116
if (canInterrupt)
117117
execution.record(promise.get());
118-
execution.cancelled = true;
119-
execution.interrupted = canInterrupt;
120118
future.cancelDelegates(canInterrupt, false);
121119
}
122120
return null;

src/test/java/net/jodah/failsafe/AsyncFailsafeTest.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -354,8 +354,14 @@ private void assertCancel(Function<FailsafeExecutor<?>, Future<?>> executorCalla
354354
}
355355

356356
public void shouldCancelOnGetAsync() throws Throwable {
357-
assertCancel(executor -> getAsync(executor, (CheckedSupplier<?>) () -> {
358-
Thread.sleep(1000);
357+
assertCancel(executor -> getAsync(executor, (ContextualSupplier<?>) ctx -> {
358+
try {
359+
waiter.assertFalse(ctx.isCancelled());
360+
Thread.sleep(1000);
361+
} catch (InterruptedException e) {
362+
waiter.assertTrue(ctx.isCancelled());
363+
throw e;
364+
}
359365
return "test";
360366
}), retryAlways);
361367
}

0 commit comments

Comments
 (0)