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
1349 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:
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
Latest Issues
Install JAVA
From 1970-01-01 08:00:00
0
0
0
Unable to install java
From 1970-01-01 08:00:00
0
0
0
Can java be used as the backend of the web?
From 1970-01-01 08:00:00
0
0
0
Is this in Java language?
From 1970-01-01 08:00:00
0
0
0
Help: JAVA encrypted data PHP decryption
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template