Posts

Showing posts from November, 2025

Simple in memory cache with plain Java

The following example is simple in memory cache using plain java without using any third party cache libraries. The below implementation shows expiry time based cache eviction and setting maximum cache size. If used with Spring Framework, it is ideal to make this class as DisposableBean to safely execute the shutdown method during application shutdown event. As below @Component public class SimpleCache implements DisposableBean { @Override public void destroy () throws Exception { shutdown(); } } Full implementation: import java.time.Duration ; import java.time.Instant ; import java.util.Comparator ; import java.util.Objects ; import java.util.UUID ; import java.util.concurrent.ConcurrentHashMap ; import java.util.concurrent.Executors ; import java.util.concurrent.ScheduledExecutorService ; import java.util.concurrent.TimeUnit ; public class SimpleCache { public record HeavyObject ( UUID id , String firstName , String lastName ) { } private record CacheValue (...