CodexBloom - Programming Q&A Platform

Investigating Memory Leaks in a Java Spring Boot Application Under Load

๐Ÿ‘€ Views: 31 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-09-21
spring-boot memory-leaks performance caching jvm Java

Quick question that's been bugging me - I've looked through the documentation and I'm still confused about Recently started profiling a Java Spring Boot application under heavy load and have identified significant memory usage spikes during peak hours. Our application handles numerous concurrent requests, and it seems to be struggling with garbage collection. While monitoring the JVM, I observed that the heap size climbs rapidly, leading to eventual OutOfMemoryErrors. Previously, I implemented some caching strategies using Ehcache, but it doesn't appear to alleviate the memory pressure as expected. Hereโ€™s a snippet of the caching configuration: ```java @Bean public CacheManager cacheManager() { return new EhCacheCacheManager(ehCacheFactoryBean().getObject()); } @Bean public EhCacheFactoryBean ehCacheFactoryBean() { EhCacheFactoryBean bean = new EhCacheFactoryBean(); bean.setConfigLocation(new ClassPathResource("ehcache.xml")); bean.setShared(true); return bean; } ``` I've also tried **tuning the JVM parameters**: ```bash -XX:+UseG1GC -Xms512m -Xmx2048m -XX:MaxGCPauseMillis=200 ``` However, the increase in memory usage persists. After conducting heap dumps using VisualVM, I found that a substantial amount of memory is consumed by session objects. The session timeout is set to 30 minutes, which seems excessive given our usage patterns. Additionally, I suspect there could be some long-lived references causing memory retention, especially in static lists used for holding user sessions. Hereโ€™s a simplified version of the code: ```java private static List<UserSession> activeSessions = new ArrayList<>(); public void addSession(UserSession session) { activeSessions.add(session); } ``` This static list grows indefinitely as users interact with the application, which might be part of the problem. Iโ€™m considering switching to a weak reference approach or using a concurrent data structure like `ConcurrentHashMap` to manage these sessions more effectively. Before proceeding with these changes, I would like to gather insights on the best practices for managing session data in a high-load Spring Boot application. Any recommendations on tools for deeper analysis or strategies for cleaning up stale objects would be greatly appreciated. Also, if anyone has experience with memory profiling in production environments, your tips would be invaluable. This is part of a larger application I'm building. Thanks in advance!