Concurrency in Play 2.1 or higher

I read a few concurrency tutorials on Play and found some examples:

Asynchronous job

import scala.concurrent.{ExecutionContext, future} def sendEmailAsync(from: String, to: String, subject: String, body: String) = { import ExecutionContext.Implicits.global // in scala.concurrent future { EmailHelper.sendEmail(from, to, subject, body) } } 

Scheduled task

 import play.api.libs.concurrent.{Akka, Execution} def sendEmailOnSchedule(from: String, to: String, subject: String, body: String) = { import scala.concurrent.duration._ import Execution.Implicits.defaultContext // in play.api.libs.concurrent Akka.system.scheduler.scheduleOnce(10 seconds) { EmailHelper.sendEmail(from, to, subject, body) } } 

Well, I'm a little confused ... the first example uses scala.concurrent.ExecutionContext.Implicits.global , and the second example uses play.api.libs.concurrent.Execution.Implicits.defaultContext . What for? Can someone explain to me what is going on behind the scenes?

+6
source share
2 answers

Scala uses an ExecutionContext for some asynchronous things (Futures, Promises). An ExecutionContext can be thought of as a thread pool in which Runnables can be sent to run on one of the threads. (This is not necessarily always a thread pool, but it tends to be).

The way you use ExecutionContext is usually passed as an argument to the implicit function that will use it. You often see method signatures as follows:

 def doAsyncThings(args: Args)(implicit exc: ExecutionContext): Future[Result] 

The doAsyncThings method will use an implicit exc , which will be passed to put the work in a separate thread.

To answer your question, the Implicits import from the two examples is the implicit ExecutionContext instances that are needed to call the future and scheduleOnce methods. For research purposes, it does not matter which one you use. global one of the scala library contains (iirc) a pool of threads with 8 threads. I would suggest that the game is similar. If you are not overly careful about which threads do any work, the choice should not affect you.

+3
source

I would suggest that the difference comes from "10 seconds." the ability to literally name times that are not built into the language. "seconds" are implicitly converted to DurationInt.

-2
source

All Articles