Frage

As far as I understand ThreadLocal variables maintain a separate copy of the variable for each thread. This variable whose multiple copies are maintained is essentially a shared variable. So what does it mean to say that a variable value can have multiple copies? How is consistency maintained so that the values of the copies do not get out of sync?

War es hilfreich?

Lösung

Your statement This variable whose multiple copies are maintained is essentially a shared variable is exactly wrong.

The ThreadLocal is set up so that it is never a shared variable. There is no need to sync it at all. Find the source for thread local and you will see.... from GrepCode we can see that it has a separate instance per thread:

public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null)
            return (T)e.value;
    }
    return setInitialValue();
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top