Created
November 14, 2022 12:05
-
-
Save darkjh/fd84c945474dd163a342017e40a9e375 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.time.Duration; | |
import java.util.concurrent.CompletableFuture; | |
import java.util.function.Supplier; | |
import net.jodah.failsafe.Failsafe; | |
import net.jodah.failsafe.RetryPolicy; | |
import net.jodah.failsafe.Timeout; | |
public class FailsafeDemo { | |
public static void main(String[] args) throws Exception { | |
Supplier<CompletableFuture<Long>> taskSupplier = () -> { | |
System.out.println("task start"); | |
var future = new CompletableFuture<Long>(); | |
// complete above future in 1 second in a dedicated thread | |
var t = new Thread( | |
() -> { | |
try { | |
Thread.sleep(1000L); | |
} catch (InterruptedException ignored) { | |
System.out.println("interrupt"); | |
} | |
future.complete(123L); | |
}); | |
t.start(); | |
return future; | |
}; | |
var retryPolicy = | |
new RetryPolicy<>() | |
.withDelay(Duration.ofMillis(50)) | |
.withMaxAttempts(2) | |
.onRetryScheduled(__ -> System.out.println("schedule")) | |
.onRetry(__ -> System.out.println("retry")) | |
.onFailedAttempt(__ -> System.out.println("retry failure")) | |
.onFailure(__ -> System.out.println("all failed")); | |
var timeoutPolicy = Timeout | |
.of(Duration.ofMillis(20)) | |
.withInterrupt(true) | |
.onFailure(__ -> System.out.println("timeout")) | |
.onSuccess(__ -> System.out.println("no timeout")); | |
var task = Failsafe.with(retryPolicy, timeoutPolicy) | |
.getStageAsync( | |
() -> taskSupplier.get() | |
.thenAccept(__ -> System.out.println("some transform"))); | |
task.whenComplete((__, e) -> System.out.println(e)); | |
Thread.sleep(5000L); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment