ThreadLocal & Memory Leak

PermGen exhaustions in combination with ThreadLocal are often caused by classloader leaks. An example: Imagine an application server which has a pool of worker threads. They will be kept alive until application server termination. A deployed web application uses a static ThreadLocal in one of its classes in order to store some thread-local data, an … 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

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

Performance of ThreadLocal variable

In 2009, some JVMs implemented ThreadLocal using an unsynchronised HashMap in the Thread.currentThread() object. This made it extremely fast (though not nearly as fast as using a regular field access, of course), as well as ensuring that the ThreadLocal object got tidied up when the Thread died. Updating this answer in 2016, it seems most … 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

What does the thread_local mean in C++11?

Thread-local storage duration is a term used to refer to data that is seemingly global or static storage duration (from the viewpoint of the functions using it) but, in actual fact, there is one copy per thread. It adds to the current options: automatic (exists during a block or function); static (exists for the program … Read more

When and how should I use a ThreadLocal variable?

One possible (and common) use is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object (I’m looking at you, SimpleDateFormat). Instead, give each thread its own instance of the object. For example: public class Foo { // SimpleDateFormat is not thread-safe, so give one to … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)