Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is execution context in Scala?

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?

like image 370
Lifu Huang Avatar asked Oct 09 '16 01:10

Lifu Huang


People also ask

What is execution context in spark?

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).

What is an executor Scala?

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.

What is execution context in Java?

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.

What is await result in Scala?

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.


1 Answers

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.

like image 51
Isvara Avatar answered Oct 13 '22 01:10

Isvara