Search code examples
multithreadingscalajava.util.concurrent

Behavior of the Scala global thread pull between instances


I'm not clear on the behavior of scala.concurrent.ExecutionContext.Implicits.global

is the thread pull a global "singleton" per process or is it local to the instance that is scoped to it? If it is scoped how can you avoid over allocation of threads?

For example in a highly threaded environment is the thread pool going to be global for all of these instances or is it going to be per each instance?

Contrived example

MyClass.scala
import scala.concurrent.ExecutionContext.Implicits.global
class MyClass {
  ...
  ...
  Future {
     for( var x <- Range ){
        Future {new MyClass} // create a new instance recursively asyncly
     }
  }
  ...
  ...
}

Solution

  • It is a global singleton per process.

    You can verify this by looking at the source, and seeing that it's an object defined in a top-level object, so in more classic terms, a "lazy val defined in a singleton".

    By the way, you can have more information about its properties in the comments of the ExecutionContext object.