I need to cache some objects with fairly heavy creation times, and I need exactly-once creation semantics. It should be possible to create objects for different CacheKeys concurrently. I think I 开发者_高级运维need something that (under the hood) does something like this:
ConcurrentHashMap<CacheKey, Future<HeavyObject>>
Are there any existing open-source implementations of this that I can re-use ?
Have you looked at Guava's MapMaker
class? I think it will do everything you need - although instead of providing a Future
, you give the class a Function<? super K, ? extends V>
which is used to compute the value.
Looking back over your post, if you really need to put values in there rather than computing them, it won't work as well - but I'll leave the suggestion here in case a computing map is okay for you.
If you need some advanced java cache look at Ehcache or JBoss Cache.
I've used the second one and although it's not developed (the effort is targeted to new Infinispan project), it works well. You can use cacheloaders for custom object-to-cache logic.
精彩评论