首先先来了解线程的两个名词,
发布:个人理解为,将原本在代码块(作用域)中的局部变量,传递出去。能使其他对象访问到。
溢出:当某个不应该被发布的对象被发布叫溢出。
public class ThreadLocalTest {
public static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>();
public static void main(String[] args) throws SQLException {
}
//jdbc获取连接,和关闭连接,这样会频繁的创建连接和关闭连接,使系统开销增大。
public static void orignGetConnection() throws SQLException{
//这个是
Connection connection = DriverManager.getConnection("url", "user", "pass");
connection.close();
}
public static Connection getConnection() throws SQLException{
Connection connection = connectionHolder.get();
if (connection==null) {
connection =DriverManager.getConnection("url", "user", "pass");
//将连接放到threadlocal中,这样可以使用,当前线程中获取到的都是同一个数据库连接。
connectionHolder.set(connection);
return connection;
}
return connection;
}
}
/**
* ThreadLocal的get方法
* public T get() {
Thread t = Thread.currentThread();//获取到当前的线程对象
ThreadLocalMap map = getMap(t);//在Thread类中有一个ThreadLocal.ThreadLocalMap成员变量
if (map != null) {//如果map不为null,则返回当前Thread类中的ThreadLocalMap成员变量的Entry对象获取Entry的存在的value值
ThreadLocalMap.Entry e = map.getEntry(this);//ThreadLocalMap有一个Entry域。
if (e != null)
return (T)e.value;
}
return setInitialValue();//如果map为null则new ThreadLocalMap,当前threadlocal对象作为key,value为null
}
*/