Gili
Gili

Reputation: 90101

Do unreferenced ThreadLocals get initialized?

Assuming a system contains 2 threads. One of them interacts with a ThreadLocal while the other does not.

What happens to ThreadLocal in the class that does not interact with the ThreadLocal?

  1. Is it ever initialized?
  2. Does it take up any memory?

Upvotes: 1

Views: 156

Answers (3)

Vlad
Vlad

Reputation: 1763

There will be only one ThreadLocal object. Each Thread has a lazily initialised map of values of all initialised ThreadLocal objects. It means only the first Thread will have an extra Map object with one value, and nothing will change for the second thread.

See ThreadLocal.setInitialValue() for details:

private T setInitialValue() {
    T value = initialValue();
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
    return value;
}

and ThreadLocal.set():

public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

Upvotes: 1

Grooveek
Grooveek

Reputation: 10094

From the javadoc :

each thread that accesses one (via its get or set method) has its own, 
independently initialized copy of the variable.

each Thread instance (from Thread.currentThread()) holds a map of ThreadLocal objects it interact with. It have a field threadLocals, each of these instances are initialized in the Thread instance.

Upvotes: 1

NPE
NPE

Reputation: 500673

From the Javadoc:

protected T initialValue()

This method will be invoked the first time a thread accesses the variable with the get() method, unless the thread previously invoked the set(T) method, in which case the initialValue method will not be invoked for the thread. Normally, this method is invoked at most once per thread, but it may be invoked again in case of subsequent invocations of remove() followed by get().

This suggests that the ThreadLocal only gets initialized for the threads that interact with it.

As to your second question (whether it uses up any resources), the answer it likely to depend on the OS.

Upvotes: 1

Related Questions