Use case of scala.concurrent.blocking
I came across the scala.concurrent.blocking
method, and according to the Scala documentation this is...
Used to designate a piece of code which potentially blocks, allowing the current BlockContext to adjust the runtime's behavior. Properly marking blocking code may improve performance or avoid deadlocks.
I have some doubts:
- what is the factor with which new threads will be spawned?
- Is this applicable only for
scala.concurrent.ExecutionContext.Implicits.global
execution context or for user-created execution contexts as well? - What happens if I wrap any executable with
blocking {
...}
? - Any practical use case where we should use this construct.
Solution 1:
- The new threads are spawned in the fork/join pool when it detects
that all the threads in the fork/join pool are waiting on each other
using the
join
construct, and there is more work to be completed that could potentially finish one of the threads. Alternatively, if one of theForkJoinWorker
threads is executing code that blocks other than by usingjoin
, it can notify the pool usingManagedBlocker
s. - It is potentially applicable to any kind of execution contexts -- it serves as a notification to the
ExecutionContext
implementation that the code executed by a worker thread is potentially blocking on some condition, and that this condition might be resolved by computing something else using some other thread. The execution context may or may not act on this. In the current (2.10, 2.11) implementation,blocking
will work only with the default global execution context. - If you wrap any executable with blocking you will induce a bit of runtime overhead, so don't always do it.
- If you have a computation that lasts a long time, e.g. seconds or minutes, or you are waiting on a future to complete using
Await
, or you are waiting on a monitor's condition to become resolved, and this condition can be resolved by some other task/future that should execute on the same execution context -- in all these cases you should useblocking
.
EDIT:
Consider taking a look at Chapter 4 in the Learning Concurrent Programming in Scala book.