CodexBloom - Programming Q&A Platform

Tomcat 9 memory leak with Spring WebSocket and session management

👀 Views: 77 💬 Answers: 1 📅 Created: 2025-06-04
spring tomcat websocket memory-leak java

I'm following best practices but Does anyone know how to I'm experiencing a memory leak issue with my Tomcat 9 server when using Spring WebSocket alongside session management. My application is designed to maintain user sessions while handling real-time messages, but over time, the memory usage escalates significantly, leading to OutOfMemoryError exceptions. I've tried the following approaches to resolve the issue: 1. I've ensured that my WebSocket connections are being closed properly on the client side, but the server still retains references to the session objects. 2. I've added the `@EnableWebSocket` annotation in my configuration class and overridden the `registerWebSocketHandlers` method to manage my WebSocket handlers. 3. I've also explicitly removed session attributes in the `@OnClose` method of my WebSocket handler, but it hasn’t made a noticeable difference. Here's a snippet of my WebSocket configuration: ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new MyWebSocketHandler(), "/ws").setAllowedOrigins("*"); } } ``` And in my WebSocket handler: ```java public class MyWebSocketHandler extends TextWebSocketHandler { @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { // Store session in a concurrent map for later use SessionRegistry.addSession(session); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // Remove session from the registry to avoid memory leak SessionRegistry.removeSession(session); } } ``` After a few hours of operation, I inspect the heap dump and notice lingering WebSocketSession objects and their associated attributes even after users log out. Can anyone suggest effective strategies to ensure that sessions are fully cleaned up, or any specific configurations that I might have overlooked to address this memory leak? I’m currently using Spring Boot 2.5.4, with Tomcat 9.0.54 embedded, and I've configured session management with the default settings. The logs also report several warnings about large objects remaining in memory, which seems to correlate with the WebSocket sessions. Any insights would be greatly appreciated! Could someone point me to the right documentation? I'm working with Java in a Docker container on Ubuntu 22.04. Is this even possible?