Futures patterns
Dependency
Akka offers tiny helpers for use with Future
sCompletionStage
. These are part of Akka’s core module:
- sbt
libraryDependencies += "com.typesafe.akka" % "akka-actor_$scala.binary_version$" % "2.6.8"
- Maven
<dependency> <groupId>com.typesafe.akka</groupId> <artifactId>akka-actor_$scala.binary_version$</artifactId> <version>2.6.8</version> </dependency>
- Gradle
dependencies { compile group: 'com.typesafe.akka', name: 'akka-actor_$scala.binary_version$', version: '2.6.8' }
After
akka.pattern.after
akka.pattern.Patterns.after
makes it easy to complete a Future
CompletionStage
with a value or exception after a timeout.
- Scala
-
val delayed = akka.pattern.after(200.millis)(Future.failed(new IllegalStateException("OHNOES"))) val future = Future { Thread.sleep(1000); "foo" } val result = Future.firstCompletedOf(Seq(future, delayed))
- Java
-
import akka.pattern.Patterns; CompletionStage<String> failWithException = CompletableFuture.supplyAsync( () -> { throw new IllegalStateException("OHNOES1"); }); CompletionStage<String> delayed = Patterns.after(Duration.ofMillis(200), system, () -> failWithException);
Retry
akka.pattern.retry
akka.pattern.Patterns.retry
will retry a Future
CompletionStage
some number of times with a delay between each attempt.
- Scala
-
import akka.actor.typed.scaladsl.adapter._ implicit val scheduler: akka.actor.Scheduler = system.scheduler.toClassic implicit val ec: ExecutionContext = system.executionContext //Given some future that will succeed eventually @volatile var failCount = 0 def futureToAttempt() = { if (failCount < 5) { failCount += 1 Future.failed(new IllegalStateException(failCount.toString)) } else Future.successful(5) } //Return a new future that will retry up to 10 times val retried: Future[Int] = akka.pattern.retry(() => futureToAttempt(), attempts = 10, 100 milliseconds)
- Java
-
import akka.pattern.Patterns; Callable<CompletionStage<String>> attempt = () -> CompletableFuture.completedFuture("test"); CompletionStage<String> retriedFuture = Patterns.retry(attempt, 3, java.time.Duration.ofMillis(200), system);