關于ThreadLocalMap<ThreadLocal,?Object>弱引用問題:
當線程沒有結束,但是ThreadLocal已經被回收,則可能導致線程中存在ThreadLocalMap<null,?Object>的鍵值對,造成內存泄露。(ThreadLocal被回收,ThreadLocal關聯的線程共享變量還存在)。
雖然ThreadLocal的get,set方法可以清除ThreadLocalMap中key為null的value,但是get,set方法在內存泄露后并不會必然調用,所以為了防止此類情況的出現,我們有兩種手段。
1、使用完線程共享變量后,顯示調用ThreadLocalMap.remove方法清除線程共享變量;
2、JDK建議ThreadLocal定義為private static,這樣ThreadLocal的弱引用問題則不存在了。
?
最常見的ThreadLocal使用場景為 用來解決 數據庫連接、Session管理等。
private static ThreadLocal<Connection> connectionHolder= new ThreadLocal<Connection>() {public Connection initialValue() {return DriverManager.getConnection(DB_URL);}};public static Connection getConnection() {return connectionHolder.get(); }
private static final ThreadLocal threadSession = new ThreadLocal();public static Session getSession() throws InfrastructureException {Session s = (Session) threadSession.get();try {if (s == null) {s = getSessionFactory().openSession();threadSession.set(s);}} catch (HibernateException ex) {throw new InfrastructureException(ex);}return s; }
?
?
http://blog.csdn.net/lhqj1992/article/details/52451136
http://www.cnblogs.com/onlywujun/p/3524675.html
?
https://www.cnblogs.com/coshaho/p/5127135.html
http://www.cnblogs.com/dolphin0520/p/3920407.html
?