Thoughts on systems, software, and what actually matters.
Monitoring HttpSession memory leak during JavaEE development

Monitoring HttpSession memory leak during JavaEE development

In my previous post I have provided a sample servlet filter to monitor non-serializable objects in HttpSession to make the JavaEE application compatible for clustered environment. We have enhanced the same servlet filter to log HttpSession object size which is helping us to find the memory leak during the development.

Here is the enhanced filter code:

public class SessionMonitorFilter implements Filter {
    
    public void doFilter(ServletRequest request, ServletResponse response, 
                         FilterChain chain) throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession(false);
        
        if (session != null) {
            logSessionSize(session);
        }
        
        chain.doFilter(request, response);
    }
    
    private void logSessionSize(HttpSession session) {
        // Calculate session size and log warnings if too large
        long size = calculateSize(session);
        if (size > 1024 * 1024) { // 1MB threshold
            logger.warn("Large session detected: " + size + " bytes");
        }
    }
}

This filter helps identify sessions that are growing too large, which is often an indicator of memory leaks.