Use of ThreadLocal in Java

ThreadLocal is mainly used to store data for the current thread, which can only be accessed by the current thread.

When defining ThreadLocal, we can also define specific types of objects stored in ThreadLocal.

ThreadLocal<Integer> threadLocalValue = new ThreadLocal<>();

Above, we defined a ThreadLocal object that stores integers.

It is also very simple to store and obtain the objects in ThreadLocal. You can use get() and set():

threadLocalValue.set(1);
Integer result = threadLocalValue.get();

I can think of ThreadLocal as a map, and the current thread is the key in the map.

In addition to a ThreadLocal object, we can also:

    public static <S> ThreadLocal<S> withInitial(supplier<? extends S> supplier) {
        return new SuppliedThreadLocal<>(supplier);
    }

The static method withinitial provided by ThreadLocal initializes a ThreadLocal.

ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 1);

Withinitial requires a supplier object, and the initial value is obtained by calling the supplier's get () method.

To delete the stored data in ThreadLocal, call:

threadLocal.remove();

Let me compare two examples to see the benefits of using ThreadLocal.

In practical applications, we usually need to store different user information for different user requests. Generally speaking, we need to build a global map to store different user information according to different user IDs for easy access later.

Storing user data in a map

Store user data in ThreadLocal

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>