Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadLocal garbage collection

From javadoc

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).

from that it seems that objects referenced by a ThreadLocal variable are garbage collected only when thread dies. But what if ThreadLocal variable a is no more referenced and is subject for garbage collection? Will object references only by variable a be subject to garbage collection if thread that holds a is still alive?

for example there is following class with ThreadLocal variable:

public class Test {
    private static final ThreadLocal a = ...; // references object b
}

This class references some object and this object has no other references to it. Then during context undeploy application classloader becomes a subject for garbage collection, but thread is from a thread pool so it does not die. Will object b be subject for garbage collection?

like image 889
michael nesterenko Avatar asked Jun 14 '13 08:06

michael nesterenko


People also ask

What is ThreadLocal in Java?

The ThreadLocal class is used to create thread local variables which can only be read and written by the same thread. For example, if two threads are accessing code having reference to same threadLocal variable then each thread will not see any modification to threadLocal variable done by other thread.

Should Java ThreadLocal be static?

ThreadLocal s should be stored in static variables to avoid memory leaks. If a ThreadLocal is stored in an instance (non-static) variable, there will be M \* N instances of the ThreadLocal value where M is the number of threads, and N is the number of instances of the containing class.

What is ThreadLocal withInitial?

withInitial does not create an InheritableThreadLocal . It only creates a regular ThreadLocal , which is why you see temp in the output. withInitial is a static method, so it can't be overridden by InheritableThreadLocal to do something different instead, like returning an InheritableThreadLocal .

Does MDC use ThreadLocal?

Internally, MDC uses ThreadLocal and it has some predefined functionalities like adding a prefix to every log.


1 Answers

ThreadLocal variables are hold in Thread

ThreadLocal.ThreadLocalMap threadLocals;

which is initialized lazily on first ThreadLocal.set/get invocation in the current thread and holds reference to the map until Thread is alive. However ThreadLocalMap uses WeakReferences for keys so its entries may be removed when ThreadLocal is referenced from nowhere else. See ThreadLocal.ThreadLocalMap javadoc for details

like image 114
Evgeniy Dorofeev Avatar answered Sep 24 '22 00:09

Evgeniy Dorofeev