search
HomeJavajavaTutorialThe use of ThreadLocal in Java multi-threading

The use of ThreadLocal in Java multi-threading

Oct 17, 2018 pm 04:21 PM
javaMultithreading

The content of this article is about the use of ThreadLocal in Java multi-threading. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In a multi-threaded environment, thread synchronization must be performed when accessing non-thread-safe variables, such as using the synchronized method to access a HashMap instance. However, synchronous access will reduce concurrency and affect system performance. At this time, you can trade space for time. If we allocate an independent variable to each thread, you can use non-thread-safe variables in an asynchronous manner. We call such variables thread-local variables.

As the name suggests, thread local variables mean that each thread has its own independent copy of the variable, which cannot be accessed by other threads like ordinary local variables. Java does not provide language-level thread local variables, but provides the function of thread local variables in the class library, which is the protagonist this time ThreadLocal class.

Usage of ThreadLocal

The use of ThreadLocal in Java multi-threading

##The Java8 version of ThreadLocal has 4 shown in the figure above There are two public methods and one protected method. The first method is used to return the initial value, which is null by default. The second static method withInitial(Supplier extends S> supplier) is newly added in Java8 version, and the next three instance methods are very simple.

Before Java8, when using ThreadLocal and want to set the initial value, you need to inherit the ThreadLocal class and override the protected T initialValue() method. For example:


ThreadLocal<integer> threadLocal = new ThreadLocal<integer>() {
    @Override
    protected Integer initialValue() {
        return 0;
    }
};</integer></integer>
can be used in the Java8 version The newly added static method withInitial(Supplier extends S> supplier) is very convenient to set the initial value, for example:

ThreadLocal<integer> threadLocal = ThreadLocal.withInitial(() -> 0);

System.out.println(threadLocal.get());
threadLocal.set(16);
System.out.println(threadLocal.get());
threadLocal.remove();
System.out.println(threadLocal.get());

// 同一个线程的输出
0
16
0
Process finished with exit code 0</integer>

The principle of ThreadLocal

Then ThreadLocal is How to implement the function of thread local variables? In fact, the basic principle of ThreadLocal is not very complicated. ThreadLocal internally defines a static class ThreadLocalMap. The key of ThreadLocalMap is the ThreadLocal object. The value of ThreadLocalMap is the value stored by ThreadLocal. However, this ThreadLocalMap is maintained in the Thread class. Let’s take a look at some of the source code of ThreadLocal:

    // ThreadLocal的set方法
    public void set(T value) {
        // 获取当前线程对象
        Thread t = Thread.currentThread();
        // 获取Map
        ThreadLocalMap map = getMap(t);
        if (map != null)
            // 设置值
            map.set(this, value);
        else
            // 初始化Map
            createMap(t, value);
    }
    
    // ThreadLocal的createMap方法
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }
    
    // Thread类定义的实例域
    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;
It can be seen that the core implementation of ThreadLocal is the implementation of ThreadLocalMap. ThreadLocalMap internally declares an Entry class to store data:

static class Entry extends WeakReference<threadlocal>> {
    /** The value associated with this ThreadLocal. */
    Object value;

    Entry(ThreadLocal> k, Object v) {
        super(k);
        value = v;
    }
}</threadlocal>
ThreadLocalMap implementation There are similarities with the implementation of HashMap. For example, arrays are also used to store data and automatically expand. The difference is that the hash algorithm and the processing after hash collision are different.

        // ThreadLocalMap的set方法
        private void set(ThreadLocal> key, Object value) {

            Entry[] tab = table;
            int len = tab.length;
            // 计算在Entry[]中的索引,每个ThreadLocal对象都有一个hash值threadLocalHashCode,每初始化一个ThreadLocal对象,hash值就增加一个固定的大小0x61c88647
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal> k = e.get();
                // 如果键已存在就更新值
                if (k == key) {
                    e.value = value;
                    return;
                }
                // 代替无效的键
                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }
        
        private static int nextIndex(int i, int len) {
            return ((i + 1 You can see that ThreadLocalMap treats the Entry[] array as a ring. Starting from the calculated index position, if the index already has data, it will be judged whether the Key is the same, and if it is the same, the value will be updated. Otherwise, just wait until you find an empty position and put the value in it. The same is true when obtaining values. Starting from the calculated index position, one by one is checked to see if the keys are the same. If there are many hash collisions, the performance may not be very good. <p></p><p>The application of ThreadLocal<strong></strong><code><br></code></p><p>##The application of ThreadLocal is very wide, for example, Java engineers are very familiar with it ThreadLocal is used in the Spring framework to encapsulate non-thread-safe stateful objects, so we can declare most beans as singleton scope. When writing multi-threaded code, we can also think about whether it is better to access non-thread-safe stateful objects in a synchronous manner, or whether it is better to use ThreadLocal to encapsulate non-thread-safe stateful objects. <code><span style="font-family: 微软雅黑, Microsoft YaHei;"></span><br></code></p><p class="comments-box-content"></p>

The above is the detailed content of The use of ThreadLocal in Java multi-threading. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools