I am new to Scala, and was trying to use some parallel constructs(Future
in particular).
I found there is an implicit parameter of type ExecutionContext
. IMO, it is something similar to(and maybe more abstract than) the concept of thread pool. I have tried to learn it through documentation, but I cannot find any clear and detailed introduction about it.
Could anyone please explain what exactly execution context is in Scala? And what is the purpose of introducing execution context to the language?
An ExecutionContext is similar to an Executor: it is free to execute computations in a new thread, in a pooled thread or in the current thread (although executing the computation in the current thread is discouraged – more on that below).
The executor is an interface and in this, a single execute method is defined. This method takes a runnable object and calls its run method.
An "execution context class" is just a holder class, created by the top level of your program, which holds all of the things (like the Transaction object in the linked example) from the top level which might be needed. It's a packaged way to avoid global variables.
Await. result tries to return the Future result as soon as possible and throws an exception if the Future fails with an exception while Await. ready returns the completed Future from which the result (Success or Failure) can safely be extracted.
The basic idea is pretty simple: you have a callback that's going to be executed at some point. On what thread will it be executed? The current one? A new one? One from a pool? That's for the execution context to decide. The default one (ExecutionContext.global
) uses threads from a global pool (with a number of threads determined by how many CPU cores you have).
In other circumstances, you might want to use a different context. For example, Akka actors can use their dispatcher as an execution context.
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