Skip to content

Instantly share code, notes, and snippets.

@jriecken
Created March 3, 2017 17:29
Show Gist options
  • Save jriecken/763f7b1efde04e808e8171e48d2d0e14 to your computer and use it in GitHub Desktop.
Save jriecken/763f7b1efde04e808e8171e48d2d0e14 to your computer and use it in GitHub Desktop.
Prepare ExecutionContext without prepare method
// Something like this will likely allow propagation of thread-local information
val originalEc: ExecutionContext = ... // the actual execution context
// This will get called every time an implicit EC is necessary, effectively preparing the context
implicit def wrappedEc: ExecutionContext = {
val ctx = ...// capture thread local context here
new ExecutionContext {
override def execute(r: Runnable): Unit = originalEc.execute(new Runnable() {
override def run(): Unit {
val oldCtx = ... // get old context
try {
... // restore captured context
r.run()
} finally {
... // restore old context
}
}
})
}
}
// Just a silly example
implicit def myEc: ExecutionContext = {
println("ec prepare")
scala.concurrent.ExecutionContext.Implicits.global
}
Future(1).map(_ + 1).map(_ + 2).foreach(println)
// Output:
// ec prepare
// ec prepare
// ec prepare
// ec prepare
// 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment