前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java ThreadLocal 分析by 源码

java ThreadLocal 分析by 源码

原创
作者头像
技术蓝海
修改2021-03-18 14:21:29
3370
修改2021-03-18 14:21:29
举报
文章被收录于专栏:wannshan(javaer,RPC)

ThreadLocal 是保证线程安全的一个工具类

大概使用方式是

代码语言:javascript
复制
private ThreadLocal<StopWatch> stopWatch = new ThreadLocal<>();//定义成员变量
//方法1里
 StopWatch sw = new StopWatch();
 stopWatch.set(sw);//保存当前线程关联变量
//方法2里
 StopWatch sw = stopWatch.get(); //需要的地方取出线程关联变量
 sw.stop();

怎么和当前线程绑定做到线程隔离的

看ThreadLocal的 set 方法

代码语言:javascript
复制
public void set(T value) {
    Thread t = Thread.currentThread();//获取当前线程
    ThreadLocalMap map = getMap(t);//获取当前线程的threadLocals 变量ThreadLocalMap类型
    if (map != null)
        map.set(this, value);//已创建,就用当前ThreadLocal对象作为key保存到map
    else
        createMap(t, value);//第一次就创建
        }
代码语言:javascript
复制
void createMap(Thread t, T firstValue) {//创建map方法,复制到当前线程的threadLocals 属性里
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}

具体对象结构如下:

Thread 类定义属性threadLocals

代码语言:javascript
复制
/* ThreadLocal values pertaining to this thread. This map is maintained
 * by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;

/*
 * InheritableThreadLocal values pertaining to this thread. This map is
 * maintained by the InheritableThreadLocal class.
 * 这个是子线程可以继承的ThreadLocal属性,具体使用InheritableThreadLocal 类做存储
 */
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

子线程可以继承父线程的Threadlocal变量吗?

可以,通过inheritableThreadLocals属性子线程可以继承父线程的local变量,具体通过InheritableThreadLocal

类保存变量

代码语言:javascript
复制
private InheritableThreadLocal<StopWatch> stopWatch = new InheritableThreadLocal<>();

具体实现过程在Thread 线程初始化方法里

代码语言:javascript
复制
private void init(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 doesn't have a strong opinion of 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(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);//这一句复制父类的local变量
    /* Stash the specified stack size in case the VM cares */
    this.stackSize = stackSize;

    /* Set thread ID */
    tid = nextThreadID();
}
代码语言:javascript
复制
/**
 * Construct a new map including all Inheritable ThreadLocals
 * from given parent map. Called only by createInheritedMap.
 *
 * @param parentMap the map associated with parent thread.
 */
private ThreadLocalMap(ThreadLocalMap parentMap) {
    Entry[] parentTable = parentMap.table;
    int len = parentTable.length;
    setThreshold(len);
    table = new Entry[len];

    for (int j = 0; j < len; j++) {
        Entry e = parentTable[j];
        if (e != null) {
            @SuppressWarnings("unchecked")
            ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
            if (key != null) {
                Object value = key.childValue(e.value);
                Entry c = new Entry(key, value);
                int h = key.threadLocalHashCode & (len - 1);
                while (table[h] != null)
                    h = nextIndex(h, len);
                table[h] = c;
                size++;
            }
        }
    }
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ThreadLocal 是保证线程安全的一个工具类
  • 怎么和当前线程绑定做到线程隔离的
  • 子线程可以继承父线程的Threadlocal变量吗?
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档