Skip to content

Instantly share code, notes, and snippets.

@yanns
Created September 11, 2013 07:23
Show Gist options
  • Save yanns/6520312 to your computer and use it in GitHub Desktop.
Save yanns/6520312 to your computer and use it in GitHub Desktop.
class MDCExecutionContextExecutor(val context: java.util.Map[_, _], val delegate: ExecutionContext) extends ExecutionContextExecutor {
def execute(runnable: Runnable) {
delegate.execute(new Runnable {
def run() {
val oldContext = MDC.getCopyOfContextMap
setContextMap(context)
try {
runnable.run()
} finally {
setContextMap(oldContext)
}
}
})
}
private[this] def setContextMap(context: java.util.Map[_, _]) {
if (context == null) {
MDC.clear()
} else {
MDC.setContextMap(context)
}
}
def reportFailure(t: Throwable) = delegate.reportFailure(t)
}
class MDCExecutionContext(wrapping: ExecutionContext) extends ExecutionContext {
def execute(runnable: Runnable) = wrapping.execute(runnable)
def reportFailure(failure: Throwable) = wrapping.reportFailure(failure)
override def prepare =
new MDCExecutionContextExecutor(MDC.getCopyOfContextMap, wrapping)
}
object CustomExecutionContext {
object Implicits {
implicit lazy val defaultContext: scala.concurrent.ExecutionContext = new MDCExecutionContext(play.api.libs.concurrent.Execution.defaultContext)
}
val defaultContext = Implicits.defaultContext
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment