ThreadLocal提供了线程局部变量,可以视为内部通过一个Map(实际是内部类ThreadLocalMap)存取数据,存取数据只在同一线程有效。
下面是该类的简单模拟,实际比这复杂:
public class ThreadLocal<T>{
private Map<Runnable,T> map = new HashMap<Runnable,T>();
//把传入的参数绑定到当前线程上
public void set(T t){
map.put(Thread.currentThread(),t);
}
//从当前线程上删除对象
public void remove(){
map.remove(Thread.currentThread());
}
//获取当前线程上绑定的对象
public T get(){
return map.get(Thread.currentThread());
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
应用:
1、管理Connection,控制事物开启关闭
import java.sql.Connection;
import java.sql.SQLException;
/**
* 封装事物相关方法,确保dao层中使用的Connection相同
*/
public class TransactionManager {
//
private static ThreadLocal<Connection> tLocal=new ThreadLocal<>();
/**
* 从线程中获取连接
* @return
*/
public static Connection getConnection(){
Connection conn = tLocal.get();
if(conn==null){
conn=DBCPUtil.getConnection();
tLocal.set(conn);
}
return conn;
}
/**
* 开启事物
*/
public static void startTransaction(){
try {
Connection conn = getConnection();
conn.setAutoCommit(false);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 回退
*/
public static void rollback(){
try {
Connection conn = getConnection();
conn.rollback();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 提交
*/
public static void commit(){
try {
Connection conn = getConnection();
conn.commit();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 连接回到连接池,线程局部变量清空
*/
public static void release(){
try {
Connection conn = getConnection();
conn.close();
tLocal.remove();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
2、在struts2框架中,ActionContext就是通过此类控制的
static ThreadLocal<ActionContext> actionContext = new ThreadLocal<ActionContext>();
- 1
一个ThreadLocal的应用例子:
public class SourceUtil{
private static ThreadLocal<Map<String,Object>> tl=new ThreadLocal<Map<String,Object>>(){
@Override
protected synchronized Map<String,Object> initialValue(){
return new HashMap<String,Object>();
}
};
public static Map<String,Object> getSource(){
return tl.get();
}
public static void putSource(Map<String,Object> user){
tl.set(user);
}
public static void put(String key,Object value){
tl.get().put(key,value);
}
public static Object get(String key){
return tl.get().get(key);
}
public static void clear(){
tl.remove();
}
}