使用java ConcurrentHashMap实现缓存

编程入门 行业动态 更新时间:2024-10-09 14:18:47
本文介绍了使用java ConcurrentHashMap实现缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在web java应用程序中实现对重量级对象的简单缓存。但我无法弄清楚如何正确地做。

I'd like to implement a simple caching of heavyweight objects in a web java application. But I can't figure out how to do it properly.

我缺少一些东西或ConcurrentHashMap方法(putIfAbsent,...)是不够的,需要额外的同步?

Am I missing something or ConcurrentHashMap methods (putIfAbsent, ...) are not enough and additional synchronization is needed ?

有没有更好的简单API(在内存存储,没有外部配置)?

Is there a better simple API (In memory storage, no external config) to do this ?

P。

推荐答案

如果可以安全地暂时拥有多个要缓存的内容的实例,如下所示执行无锁高速缓存:

If it is safe to temporarily have more than one instance for the thing you're trying to cache, you can do a "lock-free" cache like this:

public Heavy instance(Object key) { Heavy info = infoMap.get(key); if ( info == null ) { // It's OK to construct a Heavy that ends up not being used info = new Heavy(key); Heavy putByOtherThreadJustNow = infoMap.putIfAbsent(key, info); if ( putByOtherThreadJustNow != null ) { // Some other thread "won" info = putByOtherThreadJustNow; } else { // This thread was the winner } } return info; }

多个线程可以竞相创建和添加项的项,但只有一个人应该赢得。

Multiple threads can "race" to create and add an item for the key, but only one should "win".

更多推荐

使用java ConcurrentHashMap实现缓存

本文发布于:2023-11-30 21:46:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651567.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓存   java   ConcurrentHashMap

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!