Skip to main content

Pros and Cons of ThreadLocal

ThreadLocal class provides ability to store data - in memory - that's accessible only from the current thread.  Application developers have to worry about synchronizing data access across threads.

It's the equivalent of a ConcurrentHashMap where key is thread id.

ThreadLocal<Integer> tli = new ThreadLocal<>();

But one thing to keep in mind is that ThreadLocal can easily lead to memory leaks.  When the thread no longer needs the data it should be removed from the thread local object.
ThreadLocal<Integer> tli = new ThreadLocal<>();
tli.set(100);
....
....
tli.remove()

The other thing to keep in mind is that ThreadLocal is not very useful when used with ExecutorService. If state has to be maintained across ExecutorService.execute() or submit() method
calls ThreadLocal cannot be used.  With ExecutorService, thread execution can happen on any thread in  a pool.

Comments