Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Akka and Java libraries that use ThreadLocals

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.

like image 571
Adam Gent Avatar asked Nov 03 '12 14:11

Adam Gent


1 Answers

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.

like image 90
Viktor Klang Avatar answered Sep 26 '22 20:09

Viktor Klang