ElasticJob引发的Tomcat内存泄漏问题

  • 这里记录一下遇到的一个tomcat memory leak的问题:

    • 一个使用了elastic job的webapp,在进行热部署的时候日志打印了内存泄漏异常。
  • 前置知识点
    在类使用完之后,如果满足下面的情况,类就会被卸载:
    1.该类所有的实例都已经被回收,也就是 Java 堆中不存在该类的任何实例。
    2.加载该类的ClassLoader已经被回收。
    3.该类对应的java.lang.Class对象没有任何地方被引用,没有在任何地方通过反射访问该类的方法。

  • 关于tomcat memory leak
    其实tomcat的内存泄漏,根本原因是WebAppClassloader的强引用一直有效导致不能不被回收。一般有两种常见场景:
    1.容器中创建的线程没有结束


If a webapp creates a thread, by default its context classloader is set to the one of the parent thread (the thread that created the new thread). In a webapp, this parent thread is one of tomcat worker threads, whose context classloader is set to the webapp classloader when it executes webapp code.

上面这句话的意思是说,当容器中的app创建对象时,对象的context classloader会被设置为父线程(创建本线程的线程)的class loader,通常是tomcat的worker线程,其classloader是WebAppClassloader。所以说容器中的线程,包括应用自身的线程,会持有WebAppClassloader强引用。当线程不能被正常销毁时,WebAppClassloader的强引用一直存在,WebAppClassloader不能被JVM回收,因此WebAppClassloader加载的所有类都不能被卸载,产生内存泄漏。
案例:

public class LeakingServlet extends HttpServlet {
   
        private Thread leakingThread;

        protected void doGet(HttpServletRequest request,
                        HttpServletResponse response) throws ServletException, IOException {

                if (leakingThread == null) {
                        synchronized (this) {
                                if (leakingThread == null) {
                                        leakingThread = new Thread("leakingThread") {

                                                @Override
                                                public void run() {
                                                        synchronized (this) {
                                                                try {
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值