java--ThreadLocal的理解和使用

ThreadLocal类

官方解释:

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable.ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

该类提供线程本地变量。这些变量与一般的变量不同,每个线程访问一个线程(通过get或set方法)有自己独立的变量初始化副本。ThreadLocal实例通常是私有的静态字段在类希望关联状态的线程(例如,一个用户ID或交易ID)。


例如:

public class LoginUtil {
private final static ThreadLocal<LoginUser>localUser = new ThreadLocal<LoginUser>();
publicLoginUser getLoginUser(HttpServletRequset request){
        if(localUser == null) {
            LoginUser loginUser = (LoginUser)request.getSession().getAttribute("login_user");
            localUser.set(loginUser);
        }
        returnlocalUser.get();
    }
}


在上面的例子中,每一个用户访问登录就是一个线程,然后通过ThreadLocal实例的get和set方法创建自己的独立的初始化变量。从而保证了他们登录后只能拿到自己等LoginUser信息。每个线程会“隐式”包含一份thread-local变量的副本,只要线程还处于活跃状态,就可以访问该变量;当线程停止后,如果没有其他线程持有该thread-local变量,则该变量的副本会提交给垃圾回收器。


publicT get() {}
public void set(T value) { }
publicremove() {}
protected T initialValue() { }

get()方法是用来获取ThreadLocal在当前线程中保存的变量副本,set()用来设置当前线程中变量的副本, remove() 用来移除当前
线程中变量的副本, initialValue()是一个protected方法,一般是用来在使用时进行重写的,它是一个延迟加载方法。

最常见的ThreadLocal使用场景为 用来解决 数据库连接、Session管理等。

1
2
3
4
5
6
7
8
9
10
private  static  ThreadLocal<Connection> connectionHolder  new   ThreadLocal<Connection>() {
    public  Connection initialValue() {
         return  DriverManager.getConnection(DB_URL);
    }
};
 
public  static  Connection getConnection() {
    return  connectionHolder.get();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private  static  final  ThreadLocal threadSession =  new  ThreadLocal()
 
public  static  Session getSession()  throws  InfrastructureException {
     Session session = (Session) threadSession.get();
     try  {
         if  (session ==  null ) {
            session  = getSessionFactory().openSession();
             threadSession.set(session);
         }
     catch  (HibernateException ex) {
         throw  new  InfrastructureException(ex);
     }
     return session
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值