I recently introduced Akka into my company’s website, to build Spring MVC models concurrently. Our site is very data-driven, and most of the time it takes to build a page is consumed by SQL and/or cache queries. Making these concurrent has improved page render times considerably.
In development and QA, we can turn on a query profiler that captures the time taken for each SQL and cache query. This profiler uses a ThreadLocal to store the profiling data uniquely for each request thread. Introducing Akka broke the profiler, since the actor threads did not have access to the ThreadLocal (they were still logging performance data, but to ThreadLocals in their own threads, which were not included in the aggregated output).
In order to fix this, I needed to find a way to propagate the ThreadLocal created by the servlet request thread to each actor in the hierarchy, and set the ThreadLocal within the actor’s execution thread. After a couple of failed attempts, I arrived at this solution (most credit is due to a colleague with whom I discussed the problem).
For typed actors, I implemented a custom Creator<T> and a JDK proxy. The Creator’s constructor is invoked by the request (or parent actor) thread, and sets the ThreadLocal from that thread as an instance variable. In its create method, it instantiates the actor, then creates a proxy from it.
The ThreadLocal is passed to the JDK proxy in its constructor, and the proxy then wraps the typed actor method invocation with code to set and clear the ThreadLocal in the actor thread.
And now I can create my typed actors as follows:
JDK proxies only work with interfaces, not classes, so we needed a different approach for propagating ThreadLocals to untyped actors. The solution here entails creating an abstract base class for our untyped actors, and making the onReceive() method on the base class final. The onReceive() method calls an abstract doOnReceive() method, which is wrapped with code to set and clear the ThreadLocal.
This also requires a factory (very similar to the Creator above) to pass the ThreadLocal to the actor during creation:
Untyped actors that need the ThreadLocal simply extend the base class, and are created by the factory. And Voila! All is good once again in profile land.