Skip to content
Advertisement

How to thread-safe update loadingcache value guava map

For the test, in the addCache method, I created and added a map. The card has a key “a” and a value “1111”. And key “b” for LoadingCache.

Next, I want to update the value “1111” to the value “2222”. To do this, I pass all the necessary parameters from the main method to find the value “1111”.

How can I update “1111” to “2222” in a thread-safe way?

    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");

        }



    }

Advertisement

Answer

For that specific scenario, you can just call put, which makes a thread safe update. Individual modifications to a Cache are always thread safe.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement