With reference to the third point in this accepted answer, are there any cases for which it would be pointless or bad to use blocking
for a long-running computation, whether CPU- or IO-bound, that is being executed 'within' a Future
?
It depends on the ExecutionContext
your Future
is being executed in.
Pointless:
If the ExecutionContext
is not a BlockContext
, then using blocking
will be pointless. That is, it would use the DefaultBlockContext, which simply executes the code without any special handling. It probably wouldn't add that much overhead, but pointless nonetheless.
Bad:
Scala's ExecutionContext.Implicits.global
is made to spawn new threads in a ForkJoinPool
when the thread pool is about to be exhausted. That is, if it knows that is going to happen via blocking
. This can be bad if you're spawning lots of threads. If you're queuing up a lot of work in a short span of time, the global
context will happily expand until gridlock. @dk14's answer explains this in more depth, but the gist is that it can be a performance killer as managed blocking can actually become quickly unmanageable.
The main purpose of blocking
is to avoid deadlocks within thread pools, so it is tangentially related to performance in the sense that reaching a deadlock would be worse than spawning a few more threads. However, it is definitely not a magical performance enhancer.
I've written more about blocking
in particular in this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With