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

ThreadLocal Memory Leak in Java web application - Tomcat的更多相关文章

  1. java web服务器tomcat介绍【转载】

    机器矩阵2016-08-10 22:14 java程序员亲切地称他为tom猫,看到这只猫可以说明1 服务器部署成功了 ,2 网络是联通的. 到底这只猫是什么来头呢? tomcat是Apache基金会下 ...

  2. java java web及tomcat的使用

     java web及tomcat的使用 一.什么是java web: 参考百度百科: http://baike.baidu.com/link?url=HnaWXFD7wFfPAlFMW02GV6r5p ...

  3. Java Web Application使Session永不失效(利用cookie隐藏登录)

    在做 Web Application 时,因为 Web Project 有 session 自动失效的问题,所以如何让用户登录一次系统就能长时间运行三个月,就是个问题. 后来,看到 session 失 ...

  4. java web(三) Tomcat虚拟目录映射方式

    Tomact服务器虚拟目录的映射方式 web应用开发好后若想被外界访问,需要将web应用所在的目录交给web服务器管理,这个过程称为虚拟目录的映射. 方式一:在server.xml文件的host元素中 ...

  5. Java web 项目 tomcat部署方式.

    本地做Java Web项目的时候常常会用到tomcat部署测试的问题, 这里介绍项目的部署方法: 1,配置文件的形式: 例如: 你的项目目录为:f:\workspaces\MyProject,此时使用 ...

  6. Web —— java web 项目 Tomcat 的配置 与 第一个web 项目创建

    目录: 0.前言 1.Tomcat的配置 2.第一个Web 项目 0.前言 刚刚开始接触web开发,了解的也不多,在这里记录一下我的第一个web项目启动的过程.网上教程很多,使用的java IDE 好 ...

  7. java web(一):tomcat服务器的安装和简单介绍,与eclipse关联

    一:下载tomcat安装包和安装 这个百度一下就可以了. 安装完以后进入tomcat的安装路径查看 如图所示:有几个目录简单介绍下 bin目录:   存放运行tomcat服务器的相关命令. conf目 ...

  8. JAVA and JAVA WEB with TOMCAT and ECLIPSE 学习过程中遇到的字符乱码问题及解决方法汇总(随时补充)

    JAVA语言具有跨平台,unicode字符集编码的特点. 但是在开发过程中处理数据时涉及到的字符编码问题零零散散,尤其是处理中文字符时一不留神就可能出现一堆奇奇怪怪的符号,俗称乱码. 对于乱码,究其原 ...

  9. java web 在tomcat没有正常输出

    目录 文章背景 目录 问题介绍 问题解决 说明 参考文章 版本记录 文章背景 调试程序时候突然发现一些位置设置的日志输出没有了,最后总算是解决了! 目录 问题介绍 本地运行时候的环境如下: windo ...

随机推荐

  1. N皇后问题代码

    /*.h*/ #ifndef _NQUEEN_H #define _NQUEEN_H #include<iostream> #include<vector> #include& ...

  2. epoll版http服务器

    epoll是事件通知方式接收数据,效率比轮询要高 代码: import socket import re import select def client_server(new_client,recv ...

  3. 关于Djiango中 前端多对多字段点(,)的显示问题

    去除点的方法: <td> {% for roles_son in roles.permissions.all %} {% if forloop.last %} # 利用模板语言中的循环机制 ...

  4. python爬取动态网页数据,详解

    原理:动态网页,即用js代码实现动态加载数据,就是可以根据用户的行为,自动访问服务器请求数据,重点就是:请求数据,那么怎么用python获取这个数据了? 浏览器请求数据方式:浏览器向服务器的api(例 ...

  5. [React] Write a Custom React Effect Hook

    Similar to writing a custom State Hook, we’ll write our own Effect Hook called useStarWarsQuote, whi ...

  6. Redis中的缓存雪崩与缓存穿透

    1.缓存雪崩 1.1什么是缓存雪崩? 如果我们的缓存挂掉了,这意味着我们的全部请求都跑去数据库了. 我们都知道Redis不可能把所有的数据都缓存起来(内存昂贵且有限),所以Redis需要对数据设置过期 ...

  7. PHP 鸟哥:我也曾经是“不适合”编程的人

    网名:雪候鸟,大家尊称鸟哥,惠新宸 @Laruence, 是国内最有影响力的 PHP 技术专家,PHP 开发组核心成员,PECL 开发者,Zend 公司外聘顾问.他曾供职于雅虎,百度,现在新浪微博任平 ...

  8. Cogs 1708. 斐波那契平方和(矩阵乘法)

    斐波那契平方和 ★★☆ 输入文件:fibsqr.in 输出文件:fibsqr.out 简单对比 时间限制:0.5 s 内存限制:128 MB [题目描述] ,对 1000000007 取模.F0=0, ...

  9. mint-ui 做省市选择组件

    省市的数据是动态的,其实不是动态的更好搞 <!-- 省市选择 --> <mt-popup v-model="popupVisible" position=&quo ...

  10. apache不能解析php之解决办法

    记录一下Ubuntu16.04下的apache服务器不能解析php的问题,如图所示: 对于这个Ubuntu16.04最直接最快速的解决办法就是执行如下命令: sudo apt-get install ...