这里记录一下遇到的一个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 {