ThreadLocal源码详解

目录

ThreadLocal 概述

Thread类的源码

​编辑

ThreadLocal源码

线程局部变量的特性

父线程和子线程的传递过程

第一种方式

第二种方式

总结


ThreadLocal 概述

       ThreadLocal 是 Java 提供的一种机制,用于创建线程局部变量。每个线程都可以独立地访问和修改自己的 ThreadLocal 变量,而不会影响其他线程的变量。

       ThreadLocal用大白话来说,就是每个线程都有自己的一个map集,我存取数据都是在自己的map集里面,这不就可以形成创建线程局部变量了,下面我们从源码来详细介绍一下。

Thread类的源码

    注意看了,在线程Thread对象中有两个属性都是ThreadLocalMap!

ThreadLocal.ThreadLocalMap threadLocals = null;

ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

注意看了ThreadLocalMap是Thread的一个静态内部类


        /**
         * The initial capacity -- MUST be a power of two.
         */
        private static final int INITIAL_CAPACITY = 16;

        /**
         * The table, resized as necessary.
         * table.length MUST always be a power of two.
         */
        private Entry[] table;

        /**
         * The number of entries in the table.
         */
        private int size = 0;

        /**
         * The next size value at which to resize.
         */
        private int threshold; // Default to 0

       先看一下ThreadLocalMap的属性,其实如果看过hashmap的源码或者了解hashmap的机制应该不难看懂,这跟hashmap的差不多,但是结构上ThreadLocalMap中并没有链表结构,若是发生冲突就会移位。

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

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }

      看一下ThreadLocalMap内部类Entry类,它的key是ThreadLocal<?> k,继承自WeakReference, 是一种弱引用类型。若是想了解java的各种引用可以看一下笔者的这篇文章那Java中的五种引用方式底层详解-CSDN博客

      既然是弱引用类型,当 JVM 进行垃圾回收时,只被弱引用所引用,ThreadLocal 对象没有强引用(例如,所有对它的引用都被清除),那么它会被垃圾回收。key如果被清除了这意味着 ThreadLocalMap 中的 Entry 也会被清除。

      强引用不存在的话,那么 key 就会被回收,也就是会出现我们 value 没被回收,key 被回收,导致 value 永远存在,出现内存泄漏。

ThreadLocal源码

线程局部变量的特性

独立性:每个线程都有自己的 ThreadLocal 变量副本,线程之间互不干扰。

自动清理:当线程结束时,ThreadLocal 变量会被自动清理,避免内存泄漏。

适用场景:适用于需要在多个方法中共享数据,但又希望数据不被其他线程干扰的场景,如用户会话、数据库连接等。

public class ThreadLocal<T> {
    // 存储线程局部变量的索引
    private final int threadLocalHashCode = nextHashCode();

    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }
    // 获取当前线程的值
    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();
    }

    // 设置当前线程的值
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            map.set(this, value);
        } else {
            createMap(t, value);
        }
    }


}
private static AtomicInteger nextHashCode =
        new AtomicInteger();

    /**
     * The difference between successively generated hash codes - turns
     * implicit sequential thread-local IDs into near-optimally spread
     * multiplicative hash values for power-of-two-sized tables.
     */
    private static final int HASH_INCREMENT = 0x61c88647;

    /**
     * Returns the next hash code.
     */
    private static int nextHashCode() {
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }

threadLocalHashCode:每个 ThreadLocal 实例都有一个唯一的哈希码,用于在 ThreadLocalMap 中查找,而这个底层还是AtomicInteger自增获得,这个值很特殊,它是斐波那契数 也叫 黄金分割数,可以减少哈希冲突。

get() 方法:获取当前线程的 ThreadLocal 变量值,如果没有值,则调用 setInitialValue() 方法初始化。

set() 方法:设置当前线程的 ThreadLocal 变量值,如果当前线程没有 ThreadLocalMap,则创建一个。

       不管是get方法还是set方法都是拿到threadLocals进行操作,threadLocals是线程对象的属性,所以能实现线程隔离 。

父线程和子线程的传递过程

这个传递可以有两种方法

第一种方式

通过InheritableThreadLocal

InheritableThreadLocal是继承自ThreadLocal的。

      他重写了ThreadLocal的getmap方法,拿到的是inheritableThreadLocals,在开头就说过Thread类里面有两个map,而inheritableThreadLocals就是用来传递给子线程的。

 private Thread(ThreadGroup g, Runnable target, String name,
                   long stackSize, AccessControlContext acc,
                   boolean inheritThreadLocals) {
        if (name == null) {
            throw new NullPointerException("name cannot be null");
        }

        this.name = name;

        Thread parent = currentThread();
        SecurityManager security = System.getSecurityManager();
        if (g == null) {
            /* Determine if it's an applet or not */

            /* If there is a security manager, ask the security manager
               what to do. */
            if (security != null) {
                g = security.getThreadGroup();
            }

            /* If the security manager doesn't have a strong opinion
               on the matter, use the parent thread group. */
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }

        /* checkAccess regardless of whether or not threadgroup is
           explicitly passed in. */
        g.checkAccess();

        /*
         * Do we have the required permissions?
         */
        if (security != null) {
            if (isCCLOverridden(getClass())) {
                security.checkPermission(
                        SecurityConstants.SUBCLASS_IMPLEMENTATION_PERMISSION);
            }
        }

        g.addUnstarted();

        this.group = g;
        this.daemon = parent.isDaemon();
        this.priority = parent.getPriority();
        if (security == null || isCCLOverridden(parent.getClass()))
            this.contextClassLoader = parent.getContextClassLoader();
        else
            this.contextClassLoader = parent.contextClassLoader;
        this.inheritedAccessControlContext =
                acc != null ? acc : AccessController.getContext();
        this.target = target;
        setPriority(priority);
        if (inheritThreadLocals && parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;

        /* Set thread ID */
        this.tid = nextThreadID();
    }

       这上面是Thread的构造方法,在我们new一个子线程Thread的时候会执行,重点看下面框中的代码。

        可以发现在创建线程的时候会把父线程的inheritableThreadLocal赋值给子线程,实现了一个Thread的传递。

第二种方式

父线程创建 ThreadLocal 变量:当父线程创建 ThreadLocal 变量并设置值时,该值存储在父线程的 ThreadLocalMap 中。

子线程的创建:当子线程通过父线程创建(例如使用 Thread 的构造函数)时,子线程会继承父线程的 ThreadLocalMap。但是,子线程的 ThreadLocalMap 是一个新的实例,父线程的 ThreadLocal 变量不会直接传递给子线程。

子线程访问 ThreadLocal 变量:子线程可以访问父线程的 ThreadLocal 变量,但它们的值是 null,因为子线程的 ThreadLocalMap 是独立的。如果子线程需要使用父线程的 ThreadLocal 变量,可以通过 set 方法显式设置。

public class ThreadLocalExample {
    private static ThreadLocal<String> threadLocalValue = ThreadLocal.withInitial(() -> "Initial Value");

    public static void main(String[] args) {
        // 父线程
        System.out.println("Parent Thread: " + threadLocalValue.get()); // 输出: Initial Value

        Thread childThread = new Thread(() -> {
            System.out.println("Child Thread: " + threadLocalValue.get()); // 输出: Initial Value
            threadLocalValue.set("Child Value");
            System.out.println("Child Thread after set: " + threadLocalValue.get()); // 输出: Child Value
        });

        childThread.start();

        // 等待子线程完成
        try {
            childThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 父线程再次访问
        System.out.println("Parent Thread after child: " + threadLocalValue.get()); // 输出: Initial Value
    }
}

总结

1.线程局部变量:ThreadLocal 提供了一种机制,使得每个线程可以独立地存储和访问变量,避免了线程间的干扰。

2.实现机制:通过 ThreadLocalMap 存储每个线程的 ThreadLocal 变量,确保线程安全。

3.父子线程关系:子线程不会继承父线程的 ThreadLocal 变量的值,但可以通过显式设置来使用,也可以通过inheritableThreadLocal。

这种设计使得 ThreadLocal 在多线程编程中非常有用,尤其是在需要保持线程独立状态的场景中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值