What's the difference between Future(blocking(blockingCall())) and blocking(Future(blockingCall()))? Both of these are defined in scala.concurrent._
I've looked at the scala docs and some other stack overflow answers but remain unclear on what the difference is.
blockingacts as a hint to theExecutionContextthat it contains blocking code, so that it may spawn a new thread to prevent deadlocks. This presumes theExecutionContextcan do that, but not all are made to.Let's look at each one-by-one.
This requires an implicit
ExecutionContextto execute theFuture. If theExecutionContextbeing used is aBlockContext(likescala.concurrent.ExecutionContext.Implicits.globalis), it may be able to spawn a new thread in its thread pool to handle the blocking call, if it needs to. If it isn't, then nothing special happens.This tells us that
Future(blockingCall())may be a blocking call, so it is treated the same as above. Except here,Future.applyis non-blocking, so usingblockingeffectively does nothing but add a little overhead. It doesn't matter whatExecutionContextwe're calling it from here, as it isn't blocking anyway. However, the blocking call within theFuturewill block a thread in theExecutionContextit's running on, without the hint that its blocking. So, there is no reason to ever do this.I've explained
blockingmore in depth in this answer.REPL Examples: