Search code examples
javamultithreadingthread-safetyjava.util.concurrentthread-local

How is consistency maintained for multiple copies of variables that is declared as a ThreadLocal?


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?


Solution

  • 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();
    }