机票网站开发,乐陵森林酒店家具,昆山网站建设培训班,江苏企业网站建设公司关于ThreadLocalMapThreadLocal, Object弱引用问题#xff1a; 当线程没有结束#xff0c;但是ThreadLocal已经被回收#xff0c;则可能导致线程中存在ThreadLocalMapnull, Object的键值对#xff0c;造成内存泄露。#xff08;ThreadLocal被回收#xf…关于ThreadLocalMapThreadLocal, Object弱引用问题 当线程没有结束但是ThreadLocal已经被回收则可能导致线程中存在ThreadLocalMapnull, Object的键值对造成内存泄露。ThreadLocal被回收ThreadLocal关联的线程共享变量还存在。 虽然ThreadLocal的getset方法可以清除ThreadLocalMap中key为null的value但是getset方法在内存泄露后并不会必然调用所以为了防止此类情况的出现我们有两种手段。 1、使用完线程共享变量后显示调用ThreadLocalMap.remove方法清除线程共享变量 2、JDK建议ThreadLocal定义为private static这样ThreadLocal的弱引用问题则不存在了。 最常见的ThreadLocal使用场景为 用来解决 数据库连接、Session管理等。 private static ThreadLocalConnection connectionHolder new ThreadLocalConnection() {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 转载于:https://www.cnblogs.com/genggeng/p/7477191.html