Search code examples
java-8akkaactorfuturecompletable-future

Can Akka actors and Java8 CompletableFuture's be safely combined?


As far as I understood the Akka documentation, an Akka ActorSystem contains its own thread pool to execute actors. I use Akka in a Java application that also uses Java8 futures; the latter are executed by the ForkJoinPool.commonPool(). So, actors and futures use different pools, which may defeat certain assumptions hidden in the two schedulers (e.g. the Akka scheduler might assume that futures are run on the Akka pool). Could this create any performance problems?


Solution

  • There are no hidden assumptions concerning the execution of Actors and Futures: the only guarantee that we give is that any given Actor is only executed on at most one thread at any given time. Futures observe no such restrictions, they run whenever the ExecutionContext (or ThreadPool) decides to run them.

    You will of course have to observe all the same caveats when combining Actors with Java8 Futures that also apply to Scala Futures, see the docs. In particular, never touch anything (no fields, no methods) of an Actor from within a Future task or callback. Only the ActorRef is safe.