CodexBloom - Programming Q&A Platform

Java 17 Memory Leak When Using Spring Boot and Caching with Guava

👀 Views: 3 💬 Answers: 1 📅 Created: 2025-06-03
java spring-boot guava caching Java

I'm testing a new approach and I'm sure I'm missing something obvious here, but I'm working with a memory leak scenario in my Spring Boot application which uses Guava for caching... After deploying version 1.0.3 of my application, I noticed that the memory usage steadily increases over time, eventually leading to an `OutOfMemoryError`. I've set up a simple caching mechanism for user objects like this: ```java import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import java.util.concurrent.ExecutionException; public class UserService { private LoadingCache<Long, User> userCache; public UserService() { userCache = CacheBuilder.newBuilder() .maximumSize(100) .expireAfterWrite(10, TimeUnit.MINUTES) .build(new CacheLoader<Long, User>() { @Override public User load(Long userId) throws Exception { return loadUserFromDatabase(userId); } }); } public User getUser(Long userId) throws ExecutionException { return userCache.get(userId); } private User loadUserFromDatabase(Long userId) { // Simulate database access return new User(userId, "User" + userId); } } ``` I believe I've configured the cache correctly, with a maximum size and expiration time. However, when I monitor the memory usage through the JVM tools, I notice that the `userCache` keeps growing until it hits the heap limit, which triggers the `OutOfMemoryError`. I've even tried using `userCache.invalidateAll()` on certain events, but that doesn't seem to relieve the pressure on memory. I am running Java 17 with Spring Boot 2.5.4 and Guava 30.1. I’ve also checked for potential references to user objects that might prevent them from being garbage collected, but no issues were found. Could it be that Guava’s caching mechanism retains more references than I anticipated? Any suggestions on how to properly debug or mitigate this memory leak scenario? My development environment is macOS. Any help would be greatly appreciated! This is my first time working with Java latest. Could someone point me to the right documentation?