ThreadLocal variables are infamous for creating memory leaks. A memory leak in Java is amount of memory hold by object which are not in use and should have been garbage collected, but because of unintended strong references, they still live in Java heap space. There are many ways memory leak can be caused in Java but when this memory leak is caused due to ThreadLocal variable, it’s refereed as ThreadLocal memory leak. In our last post about ThreadLocal variable, we have seen How ThreadLocal variable can make SimpleDateFormat thread-safe and also raised point that in managed environment like J2EE application server or web server like Tomcat, Jetty, WebSphere or Weblogic use of ThreadLocal should be avoided. In this post we will go little deep and find out How ThreadLocal variables creates memory leak in Java web application, much like we have seen How to fix PermGen memory leak in Tomcat. If you are not familiar with ThreadLocal variables I suggest to go through my previous post. Before going into detail let's recap How ThreadLocal class works in Java.

How ThreadLocal works in Java :

ThreadLocal in Java is a mechanism to provide separate copy of shared object to every Thread. So that they no longer shared between multiple Threads and remain thread-safe. ThreadLocal variables are stored in a special map called ThreadLocalMap which is designed to hold thread local objects, it uses WeakReferences for keys.

Since every Thread has strong reference to there copy of ThreadLocal variables, they are not garbage collected until Thread is Alive and this is what creates memory leak in a typical J2EE web application. This is explained in detail in next section “How ThreadLocal variable creates memory leak in Java”.

How ThreadLocal creates memory leak in Java

In web server and application server like Tomcat or WebLogic, web-app is loaded by a different ClassLoader than which is used by Server itself. This ClassLoader loads and unloads classes from web application. Web servers also maintains ThreadPool, which is collection of worker thread, to server HTTP requests. Now if one of the Servlet or any other Java class from web application creates a ThreadLocal variable during request processing and doesn't remove it after that, copy of that Object will remain with worker Thread and since life-span of worker Thread is more than web app itself, it will prevent the object and ClassLoader, which uploaded the web app, from being garbage collected. This will create a memory leak in Server. Now if you do this couple of time you may see java.lang.OutOfMemoryError: PermGen space . Now this brings an important question,  is it possible to to use ThreadLocal variable safely in a managed environment?  Answer is Yes,, but that requires a careful usage of ThreadLocal variable and making sure to remove the object from ThreadLocal once done.

How to use ThreadLocal safely in Java Web application

Many people use Filters to initialize and remove ThreadLocal variables. You can initialize ThreadLocal in filter, put some expensive object as ThreadLocal and once request has been processed remove it from ThreadLocal as shown in below example:

public void doFilter(ServeletRequest request, ServletResponse){
try{ //set ThreadLocal variable
chain.doFilter(request, response) }finally{
//remove threadLocal variable.
}
}
That’s all on How ThreadLocal variable creates memory leak in Java. Having said that, If not necessary or You can manage without ThreadLocal variable than it’s best to avoid using ThreadLocal in managed environments like J2EE web and application servers.

转载自:https://javarevisited.blogspot.com/2013/01/threadlocal-memory-leak-in-java-web.html

最新文章

  1. JDBC的连接和增删改和查找
  2. 自动化小应用系列----利用selenium启动多个独立的浏览器
  3. 论文笔记之: Bilinear CNN Models for Fine-grained Visual Recognition
  4. Missing access checks in put_user/get_user kernel API (CVE-2013-6282)
  5. 单点登录sso规范
  6. VC C运行时库(CRTL)的几个版本及选用
  7. centos 7 卸载 mariadb 安装mysql
  8. pods的问题处理
  9. 基于IAP和Keil MDK的远程升级设计
  10. Delphi 悬浮窗口、浮动窗口的实现
  11. iOS SVN出现的问题,在mac使用Cornerstone中无法提交提交失败处理。。。
  12. HTML 5 <embed> 标签
  13. 关于用IIS在.net平台发布网页的一些坑
  14. JS中for in 与 for of
  15. EL语言表达式 (三)【EL中的算术运算以及判断EL对象是否为空】
  16. idea 中全局查找不到文件 (两shift),单页搜索不到关键字的原因
  17. 【腾讯云】自己搭建的腾讯云服务器JavaEE环境
  18. hql语句的case when then else end问题
  19. nodejs中req.body对请求参数的解析问题
  20. R1 学习记录

热门文章

  1. 优先队列priority_queue详解
  2. python - django (视图)
  3. 在CentOS7上面搭建GitLab服务器
  4. Ubuntu16.4 内核降级
  5. UOJ226. 【UR #15】奥林匹克环城马拉松 [组合数学,图论]
  6. ShellExecute打开文件,打开文件夹的用法
  7. log4g:站在巨人的头上实现一个可配置的Go日志库
  8. [WEB安全]XSS命令总结
  9. Nodejs技巧之---Exceljs
  10. Assignment2:因果图法的介绍与示例分析