在訪問共享數據時一般使用同步。若不使用同步則能夠將對象封閉在一個線程中達到線程安全的目的,該方法稱爲線程封閉(Thread Confinement)。其中實現線程封閉中規範的方法是使用ThreadLocal類。線程封閉技術一種經常使用的使用場景是在JDBC Connection對象。
public class ConnectionHelper
{
private final static String URL = "";
private final static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>()
{
public Connection initialValue()
{
try
{
return DriverManager.getConnection(URL);
}
catch (SQLException e)
{
throw new RuntimeException("數據庫鏈接有誤");
}
}
};
public static Connection getConnection()
{
return connectionHolder.get();
}
數據庫
}安全
當初次調用ThreadLocal的get方法時就會調用intialValue來獲取初始值,能夠理解爲Thread<T>包含了Map<Thead,T>對象,但實際實現並非如此。這些特定於線程的只保存在Thread對象中,當線程終止後會被當作垃圾回收。我曾寫過《Java線程範圍變量——ThreadLocal的模擬和解釋》來模擬ThreadLocal的實現原理,請參看http://blog.csdn.net/woshixuye/article/details/10017871ide