首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Linux Tomcat 重啟報 `IllegalStateException: WebappClassLoader loadClass`:Timer 線程未正確關閉導致內存洩漏,註銷 Server.xml 兩個 Listener 可暫時繞過

     編輯:程式設計綜合問答

錯誤堆疊:

INFO: Illegal access: this web application instance has been stopped already.
Could not load org.springframework.core.NestedExceptionUtils...
at com.xxx.task.ticket.TicketTreatmentWork$3.run(TicketTreatmentWork.java:410)

伴隨大量:

SEVERE: The web application [/APP] appears to have started a thread named [Timer-0] but has failed to stop it.
This is very likely to create a memory leak.

根因

  • 應用啟動了 `Timer` / `ScheduledExecutorService` / `Thread`,**未在 `ServletContextListener.contextDestroyed` 中關閉**。
  • Tomcat 熱部署/重啟時,舊 WebApp ClassLoader 無法卸載(被線程持有),導致類加載衝突拋 `IllegalStateException`。

正規修復(代碼層)

@WebListener
public class AppLifecycle implements ServletContextListener {
    private static ScheduledExecutorService scheduler;
    
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
            Thread t = new Thread(r, "AppScheduler");
            t.setDaemon(true); // 守護線程,JVM 退出自動結束
            return t;
        });
        // 註冊業務定時任務...
    }
    
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        if (scheduler != null) {
            scheduler.shutdownNow(); // 立即中斷所有任務
            try { scheduler.awaitTermination(5, TimeUnit.SECONDS); }
            catch (InterruptedException ignored) {}
        }
        // 關閉其他線程池、連接池、Timer...
    }
}

臨時繞過(Server.xml 註銷 Listener)

<!-- 註銷這兩個 Listener 可暫時消除錯誤,但不解決根因 -->
<!-- <Listener className="org.apache.catalina.core.AprLifecycleListener" /> -->
<!-- <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" /> -->

警告:註銷 `JreMemoryLeakPreventionListener` 會失去 JVM 級內存洩漏防護(如 JDBC 驅動註銷、ThreadLocal 清理),**僅作臨時調試**,生產必須在代碼層正確關閉線程。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved