深入剖析ThreadLocal实现原理以及内存泄漏问题
關(guān)于ThreadLocalMap<ThreadLocal,?Object>弱引用問題:
當(dāng)線程沒有結(jié)束,但是ThreadLocal已經(jīng)被回收,則可能導(dǎo)致線程中存在ThreadLocalMap<null,?Object>的鍵值對(duì),造成內(nèi)存泄露。(ThreadLocal被回收,ThreadLocal關(guān)聯(lián)的線程共享變量還存在)。
雖然ThreadLocal的get,set方法可以清除ThreadLocalMap中key為null的value,但是get,set方法在內(nèi)存泄露后并不會(huì)必然調(diào)用,所以為了防止此類情況的出現(xiàn),我們有兩種手段。
1、使用完線程共享變量后,顯示調(diào)用ThreadLocalMap.remove方法清除線程共享變量;
2、JDK建議ThreadLocal定義為private static,這樣ThreadLocal的弱引用問題則不存在了。
?
最常見的ThreadLocal使用場(chǎng)景為 用來解決 數(shù)據(jù)庫(kù)連接、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
?
轉(zhuǎn)載于:https://www.cnblogs.com/genggeng/p/7477191.html
總結(jié)
以上是生活随笔為你收集整理的深入剖析ThreadLocal实现原理以及内存泄漏问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: maven -Dmaven.skip.t
- 下一篇: redis学习——数据类型