The easiest way to solve it is to demarcate the use of ThreadLocals, so you create a method as such:
def withSecurityContext[T](thunk: => T)(implicit secCtx: SecurityContextFetcher): T = {
val old = threadLocalSecurityContext.get
threadLocalSecurityContext.set(secCtx.fetch)
try thunk finally threadLocalSecurityContext.set(old)
}
Then inside your Actor or whatnot:
class MyActor extends Actor {
def receive = {
case "foo" => withSecurityContext { beAwesome() }
}
}
In general though, I'd avoid ThreadLocals because they don't really blend in with distributed systems. They only work in clearly demarcated sections.