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变量,则该变量的副本会提交给垃圾回收器。
public
T get() {}
public
void
set(T value) { }
public
remove() {}
protected
T initialValue() { }
最常见的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
}
|