threadlocal是线程私有的局部变量存储容器,可以理解成每个线程都有自己专属的存储容器,用来存储线程私有变量。threadlocal 在日常开发框架中应用广泛,但用不好也会出现各种问题,本文就此讲解一下。

1. 应用场景

threadlocal 的常见应用场景有两种:

  1. 多线程并发场景中,用来保障线程安全。
  2. 处理较为复杂的业务时,使用threadlocal代替参数的显示传递。

1.1. 保障线程安全

多线程访问同一个共享变量的时候容易出现并发问题,特别是多个线程对一个变量进行写入的时候,为了保证线程安全,一般使用者在访问共享变量的时候需要进行额外的同步措施才能保证线程安全性,如:synchronized、lock之类的锁。

threadlocal是除了加锁这种同步方式之外的一种,规避多线程访问出现线程不安全的方法。当我们在创建一个变量后,如果每个线程对其进行访问的时候访问的都是线程自己的变量,这样就不会存在线程不安全问题。

threadlocal是jdk包提供的,它提供线程本地变量,如果创建一个threadlocal变量,那么访问这个变量的每个线程都会有这个变量的一个副本,在实际多线程操作的时候,操作的是自己本地内存中的变量,从而规避了线程安全问题。

1.2. 显示传递参数

这里举几个例子:

示例1:获取接口的当前请求用户
在后台接口业务逻辑的全过程中,如果需要在多个地方获取当前请求用户的信息。通常的一种做法就是:在接口请求时,通过过滤器、拦截器、aop等方式,从session或token中获取当前用户信息,存入threadlocal中。

在整个接口处理过程中,如果没有另外创建线程,都可以直接从threadlocal变量中获取当前用户,而无需再从session、token中验证和获取用户。这种方案设计不仅提高性能,最重要的是将原本复杂的逻辑和代码实现,变得简洁明了。例如下面的这个例子:

(1)定义threadlocal变量:userprofilethread.java

public class userprofilethread {
    private static threadlocal<userprofile> user_profile_tl =new threadlocal<>();

    public static void  setuserprofile(userprofile userprofile){
        user_profile_tl.set(userprofile);
    }

    public static userprofile getuserprofile() {
        return user_profile_tl.get();
    }

    public static string getcurrentuser() {
        return optional.ofnullable(user_profile_tl.get())
                .map(userprofile::getuid)
                .orelse(userprofile.anonymous_user);
    }
}

(2)在过滤器中设置变量值:

   @override
    public void dofilter(servletrequest servletrequest, servletresponse servletresponse, filterchain filterchain) throws ioexception, servletexception {
        userprofile userprofile = null;
        // ... 验证和获取用户信息 userprofile
        userprofilethread.setuserprofile(userprofile);
        filterchain.dofilter(servletrequest, servletresponse);
    }

(3)获取当前用户信息

//获取当前用户
string uid=userprofilethread.getcurrentuser();
//获取当前用户对象
userprofile user=userprofilethread.getuserprofile();

示例2:spring框架中保证数据库事务在同一个连接下执行

要想实现jdbc事务, 就必须是在同一个连接对象中操作,多个连接下事务就会不可控,需要借助分布式事务完成。那spring框架如何保证数据库事务在同一个连接下执行的呢?

datasourcetransactionmanager 是spring的数据源事务管理器,它会在你调用getconnection()的时候从数据库连接池中获取一个connection, 然后将其与threadlocal绑定,事务完成后解除绑定。这样就保证了事务在同一连接下完成。

2. 实现原理

threadlocal类提供set/get方法存储和获取value值,但实际上threadlocal类并不存储value值,真正存储是靠threadlocalmap这个类。

每个线程实例都对应一个theadlocalmap实例,我们可以在同一个线程里实例化很多个threadlocal来存储很多种类型的值,这些threadlocal实例分别作为key,对应各自的value,最终存储在entry table数组中。
我们看看threadlocal的set方法:

public class threadlocal<t> {
 public void set(t value) {
        thread t = thread.currentthread();
        threadlocalmap map = getmap(t);
        if (map != null)
            map.set(this, value);
        else
            createmap(t, value);
    }

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

    void createmap(thread t, t firstvalue) {
        t.threadlocals = new threadlocalmap(this, firstvalue);
    }
    // 省略其他方法
}

set的逻辑比较简单,就是获取当前线程的threadlocalmap,然后往map里添加kv,k是当前threadlocal实例,v是我们传入的value。这里需要注意一下,map的获取是需要从thread类对象里面取,看一下thread类的定义。

public class thread implements runnable {
    threadlocal.threadlocalmap threadlocals = null;
    //省略其他
}

thread类维护了一个threadlocalmap的变量引用。

因此,我们可以得出如下结论:

  1. 每个线程是一个thread实例,其内部维护一个threadlocals的实例成员,其类型是threadlocal.threadlocalmap。
  2. threadlocal本身并不是一个容器,我们存取的value实际上存储在threadlocalmap中,threadlocal只是作为theadlocalmap的key。

3. 注意事项

threadlocal实例有提供remove()方法,用于回收对象,清除对应的内存占用。这个方法通常容易被忽略,而导致出现了各种问题。如下面几种:

  • 线程复用:在“获取接口的当前请求用户”的例子中,tomcat中是通过线程池来处理用户请求的,而线程池中线程是复用的。肯定会出现一个线程前后被不同用户的接口请求复用的情况,因此需要对用过的threalocal变量进行覆盖或清除。
  • 内存溢出:由于threadlocalmap的生命周期跟thread一样长,如果创建的threadlocal变量很多,即对应的key占用的内存很大,但却没有手动删除,到了一定程度就会导致内存泄漏。

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