ThreadStatic v.s. ThreadLocal: is generic better than attribute?

Something the blog post noted in the comments doesn’t make explicit, but I find to be very important, is that [ThreadStatic] doesn’t automatically initialize things for every thread. For example, say you have this: [ThreadStatic] private static int Foo = 42; The first thread that uses this will see Foo initialized to 42. But subsequent … Read more

How is Java’s ThreadLocal implemented under the hood?

All of the answers here are correct, but a little disappointing as they somewhat gloss over how clever ThreadLocal‘s implementation is. I was just looking at the source code for ThreadLocal and was pleasantly impressed by how it’s implemented. The Naive Implementation If I asked you to implement a ThreadLocal<T> class given the API described … Read more

What is “thread local storage” in Python, and why do I need it?

In Python, everything is shared, except for function-local variables (because each function call gets its own set of locals, and threads are always separate function calls.) And even then, only the variables themselves (the names that refer to objects) are local to the function; objects themselves are always global, and anything can refer to them. … Read more

How to clean up ThreadLocals

The javadoc says this: “Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist). If … Read more