ConcurrentHashMap vs ReentrantReadWriteLock based Custom Map for Reloading

后端 未结 3 574
无人及你
无人及你 2021-02-04 12:24

Java Gurus,

Currently we have a HashMap which is being read frequently and modified occasionally and w

3条回答
  •  不思量自难忘°
    2021-02-04 13:07

    This sounds a lot like Guava's Cache, though it really depends how you're populating the map, and how you compute the values. (Disclosure: I contribute to Guava.)

    The real question is whether or not you can specify how to compute your SomeApplicationObject given the input String. Just based on what you've told us so far, it might look something like this...

    LoadingCache cache = CacheBuilder.newBuilder()
       .build(
           new CacheLoader() {
             public SomeApplicationObject load(String key) throws AnyException {
               return computeSomeApplicationObject(key);
             }
           });
    

    Then, whenever you wanted to rebuild the cache, you just call cache.invalidateAll(). With a LoadingCache, you can then call cache.get(key) and if it hasn't computed the value already, it'll get recomputed. Or maybe after calling cache.invalidateAll(), you can call cache.loadAll(allKeys), though you'd still need to be able to load single elements at a time in case any queries come in between the invalidateAll and loadAll.

    If this isn't acceptable -- if you can't load one value individually, you have to load them all at once -- then I'd go ahead with Peter Lawrey's approach -- keep a volatile reference to a map (ideally an ImmutableMap), recompute the whole map and assign the new map to the reference when you're done.

提交回复
热议问题