Home  >  Article  >  Java  >  How to store and obtain java ThreadLocal objects

How to store and obtain java ThreadLocal objects

PHPz
PHPzforward
2023-04-24 18:13:171231browse

1. The set method of ThreadLocal

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

It can be seen from the set method of ThreadLocal that in the structure of ThreadLocalMap, the key stores ThreadLocal itself, and the value It is the actual stored value, that is, a copy of the variable copied by the current ThreadLocal is stored in ThreadLocalMap.

2. ThreadLocal itself does not store values. In use, ThreadLocal is used as a key to obtain the value from ThreadLocalMap. It can also be seen from the get method of ThreadLocal:

    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
}

The above is the detailed content of How to store and obtain java ThreadLocal objects. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete