ThreadLocal Variables and Scala Futures

ScalaThread-Local storage (TLS) allows static variables to be attached to the currently executing thread. The most common use of TLS is to pass global context through the call-stack without method parameters. In a web-application, this will allow data (such as the current request’s URL) to be globally available throughout the codebase – extremely useful for logging or auditing purposes.

Where TLS can fail is when the execution path moves between threads. Anywhere Futures parallelize code, execution is handled off to a random thread from a thread-pool for async execution where all TLS is lost. Futures are at the heart of new reactive web frameworks such as Play!, requiring everyone to rethink how TLS is done.

But the solution is rather simple, it lies within the ExecutionContext trait. Continue reading