Home Java javaTutorial Java thread variable ThreadLocal source code analysis

Java thread variable ThreadLocal source code analysis

May 25, 2023 pm 09:01 PM
java threadlocal

1.ThreadLocal thread variables are bound to the current thread and only save the variables of the current thread. They are isolated from other threads and cannot access the data inside.

2. ThreadLocal is used in Looper, and a Looper is created and saved in ThreadLocal.

//这里用到了泛型,ThreadLocal中只保存Looper对象。
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) { //保证Looper只被创建一次。
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper(quitAllowed));
}
Copy after login

Look at how the sThreadLocal.set() method saves data.

First get the current thread, then get the ThreadLocalMap member variable of the thread, and then save it to this map.

The key is the created ThreadLocal object, and the value is the value passed in.

  public void set(T value) {
        //拿到当前线程
        Thread t = Thread.currentThread();
        //得到一个map
        ThreadLocalMap map = getMap(t);
        if (map != null){
        // 这个map是以当前对象为key的,这个this就是 ThreadLocal的实例 sThreadLocal
            map.set(this, value);
        }else{
            createMap(t, value);
        }
    }
Copy after login
//getMap 是从Thread中拿到了一个threadLocals变量,是ThreadLocal.ThreadLocalMap 的实例。
//保存的数据也是存在了这个map中,这也就是为什么ThreadLocal是和线程绑定的,对其他线程来说是隔离的原因所在。
ThreadLocalMap getMap(Thread t) {
      return t.threadLocals;
}
Copy after login

1) Save the data if the map is not empty. Take the first branch of the if judgment above. This storage method is similar to HashMap

private void set(ThreadLocal<?> key, Object value) {
      Entry[] tab = table;
      int len = tab.length;
      // 计算出key在集合中的索引,index
      int i = key.threadLocalHashCode & (len-1);
       //开始遍历整个数组,
       //取出索引为i的Entry,如果不为空,取出下一个,进行遍历
        for (Entry e = tab[i];
               e != null;
               e = tab[i = nextIndex(i, len)]) {
              ThreadLocal<?> k = e.get();
              //如果取出的k和传进来的key一致,则把新的值存起来。
              if (k == key) {
                  e.value = value;
                  return;
              }
              //直到取出最有一个,k==null则进行存储。
              if (k == null) {
                  replaceStaleEntry(key, value, i);
                  return;
              }
          }
          //如果索引i的位置,没有Entry,则把传进来的key和value保存在这个位置。
          tab[i] = new Entry(key, value);
          int sz = ++size;
          //如果大于阈值了,则进行扩容
          if (!cleanSomeSlots(i, sz) && sz >= threshold)
              rehash();
}
Copy after login

2) Save data if the map is empty. Then create a ThreadLocalMap and assign it to the current thread t.

 void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}
Copy after login
 ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
    //创建一个大小为16的数组
    table = new Entry[INITIAL_CAPACITY];
    //计算得到的i是数组的角标。可以参考hashMap源码分析
    int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
    //赋值,保存数据
    table[i] = new Entry(firstKey, firstValue);
    size = 1;
    //扩容的阈值
    setThreshold(INITIAL_CAPACITY);
}
Copy after login

3. Let’s look at how ThreadLocal gets its value.

Also get the current thread t first, and then get its member variable ThreadLocalMap through t.

public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    //如果map不为空,则从map中取值
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    //如果map为空
    return setInitialValue();
}
Copy after login

1) If the map is not empty, get the value from the map.

//如果map不为空
 private Entry getEntry(ThreadLocal<?> key) {
    //拿到key对应的索引
    int i = key.threadLocalHashCode & (table.length - 1);
    //从数组中拿到Entry
    Entry e = table[i];
    if (e != null && e.get() == key){如果key一样直接返回
        return e;
    }else{//如果不一致则开始遍历
         return getEntryAfterMiss(key, i, e);
    }
}
Copy after login
private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
		Entry[] tab = table;
		int len = tab.length;
		while (e != null) {
			ThreadLocal<?> k = e.get();
			if (k == key)
				return e;
			if (k == null)
				expungeStaleEntry(i);
			else
				i = nextIndex(i, len);
			e = tab[i];
		}
		return null;
}
Copy after login

2) If the map obtained is empty when getting, you need to initialize it at this time

//如果map为空,则调用这个方法,initialValue由用户去实现。
private T setInitialValue() {
    T value = initialValue();
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
    return value;
}
Copy after login
//下面是Choreographer中的例子:
private static final ThreadLocal<Choreographer> sThreadInstance =
        new ThreadLocal<Choreographer>() {
    @Override
    protected Choreographer initialValue() {
        Looper looper = Looper.myLooper();
        if (looper == null) {
            throw new IllegalStateException("The current thread must have a looper!");
        }
        Choreographer choreographer = new Choreographer(looper, VSYNC_SOURCE_APP);
        if (looper == Looper.getMainLooper()) {
            mMainInstance = choreographer;
        }
        return choreographer;
    }
};
Copy after login

ThreadLocalMap is used to store ThreadLocal data. This ThreadLocalMap object is obtained from the current thread through

and is obtained from the current thread. The design of ThreadLocalMap realizes the isolation of data between different threads and only saves the data of the corresponding thread.

The ThreadLocal object itself is used as a key to store data in ThreadLocalMap. map.set(this, value);

If you want to store more data in ThreadLocalMap, you need to create multiple objects.

The above is the detailed content of Java thread variable ThreadLocal source code analysis. For more information, please follow other related articles on the PHP Chinese website!

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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles