【问题标题】:How to thread-safe update loadingcache value guava map如何线程安全更新加载缓存值番石榴图
【发布时间】:2021-10-01 05:15:22
【问题描述】:

为了测试,在 addCache 方法中,我创建并添加了一个地图。该卡具有键“a”和值“1111”。 LoadingCache 的键“b”。

接下来,我想将值“1111”更新为值“2222”。为此,我从 main 方法中传递了所有必要的参数以查找值“1111”。

如何以线程安全的方式将“1111”更新为“2222”?

    public class TestCache {


        private LoadingCache<String, Map<String, String>> attemptsCache;

        public TestCache() {

            attemptsCache = CacheBuilder.newBuilder()
                    .maximumSize(10000)
                    .expireAfterWrite(1, TimeUnit.HOURS)
                    .build(new CacheLoader<String, Map<String, String>>() {
                        @Override
                        public Map<String, String> load(@Nonnull final String key) {
                            return Map.of();
                        }
                    });
        }


        public void addCache(final String pathKey, final String inputKey, final String nameValue) {

            Map<String, String> map = new HashMap<>();
            map.put("a", "1111");
            attemptsCache.put("b", map);

            // Next, you need to update the map value

        }

        
        public static void main(String[] args) throws ExecutionException {

            new TestCache().addCache("b","a","2222");

        }



    }

【问题讨论】:

  • 在你描述的具体情况下,为什么不直接使用put?
  • @Louis Wasserman 我不知道,也许吧。我只是问问。

标签: java guava


【解决方案1】:

对于该特定场景,您只需调用put,它会进行线程安全更新。对缓存的单独修改始终是线程安全的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多