一、threadlocal简介

多线程访问同一个共享变量的时候容易出现并发问题,特别是多个线程对一个变量进行写入的时候,为了保证线程安全,一般使用者在访问共享变量的时候需要进行额外的同步措施才能保证线程安全性。threadlocal是除了加锁这种同步方式之外的一种保证一种规避多线程访问出现线程不安全的方法,当我们在创建一个变量后,如果每个线程对其进行访问的时候访问的都是线程自己的变量这样就不会存在线程不安全问题。

二、threadlocal简单使用

下面的例子中,开启两个线程,在每个线程内部设置了本地变量的值,然后调用print方法打印当前本地变量的值。如果在打印之后调用本地变量的remove方法会删除本地内存中的变量,代码如下所示

package test;

public class threadlocaltest {

    static threadlocal<string> localvar = new threadlocal<>();

    static void print(string str) {
        //打印当前线程中本地内存中本地变量的值
        system.out.println(str + " :" + localvar.get());
        //清除本地内存中的本地变量
        localvar.remove();
    }

    public static void main(string[] args) {
        thread t1  = new thread(new runnable() {
            @override
            public void run() {
                //设置线程1中本地变量的值
                localvar.set("localvar1");
                //调用打印方法
                print("thread1");
                //打印本地变量
                system.out.println("after remove : " + localvar.get());
            }
        });

        thread t2  = new thread(new runnable() {
            @override
            public void run() {
                //设置线程1中本地变量的值
                localvar.set("localvar2");
                //调用打印方法
                print("thread2");
                //打印本地变量
                system.out.println("after remove : " + localvar.get());
            }
        });

        t1.start();
        t2.start();
    }
}

下面是运行后的结果:

三、threadlocal的实现原理

下面是threadlocal的类图结构,从图中可知:thread类中有两个变量threadlocals和inheritablethreadlocals,二者都是threadlocal内部类threadlocalmap类型的变量,我们通过查看内部内threadlocalmap可以发现实际上它类似于一个hashmap。

在默认情况下,每个线程中的这两个变量都为null:

threadlocal.threadlocalmap threadlocals=null;
threadlocal.threadlocalmap inheritablethreadlocals=null;

只有当线程第一次调用threadlocal的set或者get方法的时候才会创建他们(后面我们会查看这两个方法的源码)。除此之外,和我所想的不同的是,每个线程的本地变量不是存放在threadlocal实例中,而是放在调用线程的threadlocals变量里面(前面也说过,该变量是thread类的变量)。也就是说,threadlocal类型的本地变量是存放在具体的线程空间上,其本身相当于一个装载本地变量的工具壳,通过set方法将value添加到调用线程的threadlocals中,当调用线程调用get方法时候能够从它的threadlocals中取出变量。如果调用线程一直不终止,那么这个本地变量将会一直存放在他的threadlocals中,所以不使用本地变量的时候需要调用remove方法将threadlocals中删除不用的本地变量。下面我们通过查看threadlocal的set、get以及remove方法来查看threadlocal具体实怎样工作的

1、set方法源码

public void set(t value) {
    //(1)获取当前线程(调用者线程)
    thread t = thread.currentthread();
    //(2)以当前线程作为key值,去查找对应的线程变量,找到对应的map
    threadlocalmap map = getmap(t);
    //(3)如果map不为null,就直接添加本地变量,key为当前定义的threadlocal变量的this引用,值为添加的本地变量值
    if (map != null)
        map.set(this, value);
    //(4)如果map为null,说明首次添加,需要首先创建出对应的map
    else
        createmap(t, value);
}

在上面的代码中,(2)处调用getmap方法获得当前线程对应的threadlocals(参照上面的图示和文字说明),该方法代码如下

threadlocalmap getmap(thread t) {
    return t.threadlocals; //获取线程自己的变量threadlocals,并绑定到当前调用线程的成员变量threadlocals上
}

如果调用getmap方法返回值不为null,就直接将value值设置到threadlocals中(key为当前线程引用,值为本地变量);如果getmap方法返回null说明是第一次调用set方法(前面说到过,threadlocals默认值为null,只有调用set方法的时候才会创建map),这个时候就需要调用createmap方法创建threadlocals,该方法如下所示

void createmap(thread t, t firstvalue) {
    t.threadlocals = new threadlocalmap(this, firstvalue);
}

createmap方法不仅创建了threadlocals,同时也将要添加的本地变量值添加到了threadlocals中。

2、get方法源码

在get方法的实现中,首先获取当前调用者线程,如果当前线程的threadlocals不为null,就直接返回当前线程绑定的本地变量值,否则执行setinitialvalue方法初始化threadlocals变量。在setinitialvalue方法中,类似于set方法的实现,都是判断当前线程的threadlocals变量是否为null,是则添加本地变量(这个时候由于是初始化,所以添加的值为null),否则创建threadlocals变量,同样添加的值为null。

public t get() {
    //(1)获取当前线程
    thread t = thread.currentthread();
    //(2)获取当前线程的threadlocals变量
    threadlocalmap map = getmap(t);
    //(3)如果threadlocals变量不为null,就可以在map中查找到本地变量的值
    if (map != null) {
        threadlocalmap.entry e = map.getentry(this);
        if (e != null) {
            @suppresswarnings("unchecked")
            t result = (t)e.value;
            return result;
        }
    }
    //(4)执行到此处,threadlocals为null,调用该更改初始化当前线程的threadlocals变量
    return setinitialvalue();
}

private t setinitialvalue() {
    //protected t initialvalue() {return null;}
    t value = initialvalue();
    //获取当前线程
    thread t = thread.currentthread();
    //以当前线程作为key值,去查找对应的线程变量,找到对应的map
    threadlocalmap map = getmap(t);
    //如果map不为null,就直接添加本地变量,key为当前线程,值为添加的本地变量值
    if (map != null)
        map.set(this, value);
    //如果map为null,说明首次添加,需要首先创建出对应的map
    else
        createmap(t, value);
    return value;
}

3、remove方法的实现

remove方法判断该当前线程对应的threadlocals变量是否为null,不为null就直接删除当前线程中指定的threadlocals变量

public void remove() {
    //获取当前线程绑定的threadlocals
     threadlocalmap m = getmap(thread.currentthread());
     //如果map不为null,就移除当前线程中指定threadlocal实例的本地变量
     if (m != null)
         m.remove(this);
}

如下图所示:每个线程内部有一个名为threadlocals的成员变量,该变量的类型为threadlocal.threadlocalmap类型(类似于一个hashmap),其中的key为当前定义的threadlocal变量的this引用,value为我们使用set方法设置的值。每个线程的本地变量存放在自己的本地内存变量threadlocals中,如果当前线程一直不消亡,那么这些本地变量就会一直存在(所以可能会导致内存溢出),因此使用完毕需要将其remove掉。

四、threadlocal不支持继承性

同一个threadlocal变量在父线程中被设置值后,在子线程中是获取不到的。(threadlocals中为当前调用线程对应的本地变量,所以二者自然是不能共享的)

package test;

public class threadlocaltest2 {

    //(1)创建threadlocal变量
    public static threadlocal<string> threadlocal = new threadlocal<>();

    public static void main(string[] args) {
        //在main线程中添加main线程的本地变量
        threadlocal.set("mainval");
        //新创建一个子线程
        thread thread = new thread(new runnable() {
            @override
            public void run() {
                system.out.println("子线程中的本地变量值:"+threadlocal.get());
            }
        });
        thread.start();
        //输出main线程中的本地变量值
        system.out.println("mainx线程中的本地变量值:"+threadlocal.get());
    }
}

五、inheritablethreadlocal类

在上面说到的threadlocal类是不能提供子线程访问父线程的本地变量的,而inheritablethreadlocal类则可以做到这个功能,下面是该类的源码

public class inheritablethreadlocal<t> extends threadlocal<t> {

    protected t childvalue(t parentvalue) {
        return parentvalue;
    }

    threadlocalmap getmap(thread t) {
       return t.inheritablethreadlocals;
    }

    void createmap(thread t, t firstvalue) {
        t.inheritablethreadlocals = new threadlocalmap(this, firstvalue);
    }
}

从上面代码可以看出,inheritablethreadlocal类继承了threadlocal类,并重写了childvalue、getmap、createmap三个方法。其中createmap方法在被调用(当前线程调用set方法时得到的map为null的时候需要调用该方法)的时候,创建的是inheritablethreadlocal而不是threadlocals。同理,getmap方法在当前调用者线程调用get方法的时候返回的也不是threadlocals而是inheritablethreadlocal。

下面我们看看重写的childvalue方法在什么时候执行,怎样让子线程访问父线程的本地变量值。我们首先从thread类开始说起

private void init(threadgroup g, runnable target, string name,
                  long stacksize) {
    init(g, target, name, stacksize, null, true);
}
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;
    //(1)获取当前线程(父线程)
    thread parent = currentthread();
    //安全校验
    securitymanager security = system.getsecuritymanager();
    if (g == null) { //g:当前线程组
        if (security != null) {
            g = security.getthreadgroup();
        }
        if (g == null) {
            g = parent.getthreadgroup();
        }
    }
    g.checkaccess();
    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);
    //(2)如果父线程的inheritablethreadlocal不为null
    if (inheritthreadlocals && parent.inheritablethreadlocals != null)
        //(3)设置子线程中的inheritablethreadlocals为父线程的inheritablethreadlocals
        this.inheritablethreadlocals =
            threadlocal.createinheritedmap(parent.inheritablethreadlocals);
    this.stacksize = stacksize;

    tid = nextthreadid();
}

在init方法中,首先(1)处获取了当前线程(父线程),然后(2)处判断当前父线程的inheritablethreadlocals是否为null,然后调用createinheritedmap将父线程的inheritablethreadlocals作为构造函数参数创建了一个新的threadlocalmap变量,然后赋值给子线程。下面是createinheritedmap方法和threadlocalmap的构造方法

static threadlocalmap createinheritedmap(threadlocalmap parentmap) {
    return new threadlocalmap(parentmap);
}

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++;
            }
        }
    }
}

在构造函数中将父线程的inheritablethreadlocals成员变量的值赋值到新的threadlocalmap对象中。返回之后赋值给子线程的inheritablethreadlocals。总之,inheritablethreadlocals类通过重写getmap和createmap两个方法将本地变量保存到了具体线程的inheritablethreadlocals变量中,当线程通过inheritablethreadlocals实例的set或者get方法设置变量的时候,就会创建当前线程的inheritablethreadlocals变量。而父线程创建子线程的时候,threadlocalmap中的构造函数会将父线程的inheritablethreadlocals中的变量复制一份到子线程的inheritablethreadlocals变量中。

六、从threadlocalmap看threadlocal使用不当的内存泄漏问题

1、基础概念

首先我们先看看threadlocalmap的类图,在前面的介绍中,我们知道threadlocal只是一个工具类,他为用户提供get、set、remove接口操作实际存放本地变量的threadlocals(调用线程的成员变量),也知道threadlocals是一个threadlocalmap类型的变量,下面我们来看看threadlocalmap这个类。在此之前,我们回忆一下java中的四种引用类型

①强引用:java中默认的引用类型,一个对象如果具有强引用那么只要这种引用还存在就不会被gc。

②软引用:简言之,如果一个对象具有弱引用,在jvm发生oom之前(即内存充足够使用),是不会gc这个对象的;只有到jvm内存不足的时候才会gc掉这个对象。软引用和一个引用队列联合使用,如果软引用所引用的对象被回收之后,该引用就会加入到与之关联的引用队列中

③弱引用(这里讨论threadlocalmap中的entry类的重点):如果一个对象只具有弱引用,那么这个对象就会被垃圾回收器gc掉(被弱引用所引用的对象只能生存到下一次gc之前,当发生gc时候,无论当前内存是否足够,弱引用所引用的对象都会被回收掉)。弱引用也是和一个引用队列联合使用,如果弱引用的对象被垃圾回收期回收掉,jvm会将这个引用加入到与之关联的引用队列中。若引用的对象可以通过弱引用的get方法得到,当引用的对象呗回收掉之后,再调用get方法就会返回null

④虚引用:虚引用是所有引用中最弱的一种引用,其存在就是为了将关联虚引用的对象在被gc掉之后收到一个通知。(不能通过get方法获得其指向的对象)

2、分析threadlocalmap内部实现

上面我们知道threadlocalmap内部实际上是一个entry数组

private entry[] table;

我们先看看entry的这个内部类

/**
 * 是继承自weakreference的一个类,该类中实际存放的key是
 * 指向threadlocal的弱引用和与之对应的value值(该value值
 * 就是通过threadlocal的set方法传递过来的值)
 * 由于是弱引用,当get方法返回null的时候意味着坑能引用
 */
static class entry extends weakreference<threadlocal<?>> {
    /** value就是和threadlocal绑定的 */
    object value;

    //k:threadlocal的引用,被传递给weakreference的构造方法
    entry(threadlocal<?> k, object v) {
        super(k);
        value = v;
    }
}
//weakreference构造方法(public class weakreference<t> extends reference<t> )
public weakreference(t referent) {
    super(referent); //referent:threadlocal的引用
}

//reference构造方法
reference(t referent) {
    this(referent, null);//referent:threadlocal的引用
}

reference(t referent, referencequeue<? super t> queue) {
    this.referent = referent;
    this.queue = (queue == null) ? referencequeue.null : queue;
}

在上面的代码中,我们可以看出,当前threadlocal的引用k被传递给weakreference的构造函数,所以threadlocalmap中的key为threadlocal的弱引用。当一个线程调用threadlocal的set方法设置变量的时候,当前线程的threadlocalmap就会存放一个记录,这个记录的key值为threadlocal的弱引用,value就是通过set设置的值。如果当前线程一直存在且没有调用该threadlocal的remove方法,如果这个时候别的地方还有对threadlocal的引用,那么当前线程中的threadlocalmap中会存在对threadlocal变量的引用和value对象的引用,是不会释放的,就会造成内存泄漏。

考虑这个threadlocal变量没有其他强依赖,如果当前线程还存在,由于线程的threadlocalmap里面的key是弱引用,所以当前线程的threadlocalmap里面的threadlocal变量的弱引用在gc的时候就被回收,但是对应的value还是存在的这就可能造成内存泄漏(因为这个时候threadlocalmap会存在key为null但是value不为null的entry项)。

七、总结

threadlocalmap中的entry的key使用的是threadlocal对象的弱引用,在没有其他地方对threadloca依赖,threadlocalmap中的threadlocal对象就会被回收掉,但是对应的不会被回收,这个时候map中就可能存在key为null但是value不为null的项,这需要实际的时候使用完毕及时调用remove方法避免内存泄漏。

以上就是详解java中的threadlocal的详细内容,更多关于java threadlocal的资料请关注www.887551.com其它相关文章!