首页 > 解决方案 > 如何线程安全更新 loadingcache 值番石榴图

问题描述

为了测试,在 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");

        }



    }

标签: javaguava

解决方案


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


推荐阅读