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

How to store and obtain java ThreadLocal objects

PHPz
Release: 2023-04-24 18:13:17
forward
1318 people have browsed it

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);
    }
Copy after login

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();
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template