Advertisement
Guest User

Untitled

a guest
Nov 7th, 2018
450
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.96 KB | None | 0 0
  1. package com.mdc
  2. import org.slf4j.MDC
  3.  
  4. import scala.concurrent.{ExecutionContext, ExecutionContextExecutor}
  5.  
  6. object MDCHttpExecutionContext {
  7.   def fromThread(delegate: ExecutionContext): ExecutionContextExecutor = new MDCHttpExecutionContext(delegate)
  8. }
  9.  
  10. class MDCHttpExecutionContext(delegate: ExecutionContext) extends ExecutionContextExecutor{
  11.  
  12.   override def execute(runnable: Runnable) = delegate.execute(new Runnable {
  13.     val mdcContext = MDC.getCopyOfContextMap
  14.     override def run(): Unit = {
  15.       val oldMDCContext = MDC.getCopyOfContextMap
  16.       setContextMap(mdcContext)
  17.       try {
  18.         runnable.run()
  19.       } finally {
  20.         setContextMap(oldMDCContext)
  21.       }
  22.     }
  23.   })
  24.  
  25.   private[this] def setContextMap(context: java.util.Map[String, String]) = {
  26.     if(context == null){
  27.       MDC.clear()
  28.     } else {
  29.       MDC.setContextMap(context)
  30.     }
  31.   }
  32.  
  33.   override def reportFailure(cause: Throwable) = delegate.reportFailure(cause)
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement