What has kept me from using Akka regularly (in Java) is a concern I have with libraries that use ThreadLocals.
That is I think some Akka Dispatchers may cause ThreadLocal variables to be left behind, or missing all together. So the obvious solution would be to avoid using ThreadLocals but there are so many libraries that use them: Spring, Wro4j, Log4j, etc etc...
ThreadLocals normally work fine in Servlet Container. That is because even though containers have threadpools the request is mainly a synchronous lifecycle, thus generally at the end of a request things like Spring and Wro4J will clean up there threadlocals. Some containers like Tomcat even monitor threadlocal leaks.
Such is not the case in Akka from what I understand.
How do people get around this issue?
For now I just avoid using Akka and use a Message Queue (like RabbitMQ or ActiveMQ) but would like to use Akka as it covers a wider range of async problem/solution.
I also think Netty has similar issues but I believe Netty offers some sort Channel Context object that you can use in place of ThreadLocal and in theory some libraries may know to use that instead of ThreadLocal.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With