Use case of scala.concurrent.blocking

ScalaScala 2.10

Scala Problem Overview


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.

Scala Solutions


Solution 1 - Scala

  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 the ForkJoinWorker threads is executing code that blocks other than by using join, it can notify the pool using ManagedBlockers.
  2. 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.
  3. If you wrap any executable with blocking you will induce a bit of runtime overhead, so don't always do it.
  4. 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 use blocking.

EDIT:

Consider taking a look at Chapter 4 in the Learning Concurrent Programming in Scala book.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSourav ChandraView Question on Stackoverflow
Solution 1 - Scalaaxel22View Answer on Stackoverflow