Java缓存数据读取失败:避免静态变量和单例模式的陷阱
Java应用中,缓存大量数据以提升性能是常见做法。然而,有时会遇到从缓存中读取数据失败的问题。本文分析一个案例,探讨导致Java缓存数据读取失败的原因,并提供解决方案。
案例:内存不足导致缓存数据丢失
开发者使用scenariobuffer类将约16万条资产数据加载到名为assetbuffer的HashMap中。getbasset方法用于读取缓存数据。在服务器内存不足(可用内存仅剩100MB,缓存占用3GB,总内存8GB)时,getbasset方法返回空值。重启服务器并清除缓存后,问题解决。项目使用tomcat启动,分配约3GB内存。代码如下:
立即学习“Java免费学习笔记(深入)”;
@Component @Order(1) @Slf4j public class scenariobuffer implements IActionListener, ApplicationRunner { private Static Map<String, List<Asset>> assetbuffer = Collections.synchronizedMap(new HashMap<>()); private static scenariobuffer instance = new scenariobuffer(); public static scenariobuffer getinstance() { return instance; } public static List<Asset> getbasset(String groupid) { if (assetbuffer.containsKey(groupid)) { return assetbuffer.get(groupid); } return null; } @Override public void run(ApplicationArguments args) throws Exception { IAssetService assetService = springUtil.getBean(IAssetService.class); List<Asset> assetlist = assetService.list(); assetbuffer.put("key", assetlist); } }
问题分析与解决方案
问题并非单纯的内存不足导致jvm清空数据,而是代码设计缺陷:
-
不当使用static和getinstance(): scenariobuffer类使用static关键字,使其成为单例。但getinstance()方法冗余,因为Spring容器已保证@Component注解的Bean是单例的。static关键字导致assetbuffer成为静态变量,生命周期与应用服务器相同,即使JVM垃圾回收,也难以回收其内存。
-
不推荐的Bean获取方式: 使用SpringUtil.getBean(IAssetService.class)获取Bean,不推荐。Spring框架推荐使用@Autowired或@Resource注解进行依赖注入。
-
初始化时机问题: 使用ApplicationRunner接口在应用启动时初始化缓存,但更好的方式是使用@PostConstruct注解或实现InitializingBean接口,使初始化过程更明确可控。
改进后的代码
修改scenariobuffer类及其使用方法:
@Component public class scenariobuffer implements IActionListener { private Map<String, List<Asset>> assetbuffer = new HashMap<>(); @Autowired private IAssetService assetservice; @PostConstruct public void init() { List<Asset> assetlist = assetservice.list(); assetbuffer.put("key", assetlist); } public List<Asset> getbasset(String groupid) { return assetbuffer.get(groupid); } }
在其他服务类中,使用@Resource注解注入scenariobuffer:
@Service public class XxxService { @Resource private ScenarioBuffer scenarioBuffer; public void xxx() { List<Asset> asset = scenarioBuffer.getBAsset("xxx"); } }
改进后,避免了不必要的静态变量和单例获取方法,利用Spring框架的依赖注入机制和@PostConstruct注解,使代码更清晰、易于维护,并减少了内存泄漏的风险。即使服务器内存紧张,JVM垃圾回收机制也能更有效工作,降低缓存数据读取失败的可能性。