ThreadLocal 适用于独立变量副本的情况,比如 Hibernate 的 session 获取场景。
示例代码:
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
public static Session getCurrentSession(){
Session session = threadLocal.get();
try {
if(session ==null&&!session.isOpen()){
//...
}
threadLocal.set(session);
} catch (Exception e) {
// TODO: handle exception
}
return session;
}