Wes
Wes

Reputation: 658

Are There Dangers to Writing to Ehcache in Parallel?

In the given example, I have an inner class that defines a read-through CacheLoaderWriter inside of an imagined ExampleCache class that would abstract cache operations so that 3rd parties just think they are access a data structure (key-value pair). My question involves the loadAll method.

If loadAll is written to write to EhCache in parallel, will there be any risks of record mutation or instability? Is EhCache built to handle user-defined concurrency?

    class ExampleCacheLoader implements CacheLoaderWriter<String, ArrayList> {


            private HashMap<String, ArrayList> map;

            public CacheLoader() {
                map = new HashMap<>();
            }

            @Override
            public ArrayList<String> load(String s) throws Exception {

                Map.Entry<String, ArrayList<String>> personEntry = getPersonAliases(s);
                if(!map.containsKey(personEntry.getKey())){
                    map.put(personEntry.getKey(), personEntry.getValue());
                }
                return map.get(personEntry.getKey());
            }

            @Override
            public Map<String, ArrayList> loadAll(
                    Iterable<? extends String> keys) throws Exception {
                Map<String, ArrayList> localTempMap = new HashMap<>();
                Stream keyStream =  StreamSupport.stream(entries.spliterator(), true);
                keyStream.forEach(key -> {
                    localTempMap.putIfAbsent(
                            getterExample(key).getKey(),
                            getterExample(key).getValue());
                });

                map.putAll(localTempMap);
                return localTempMap;
            }
            .

            .

            .

Upvotes: 3

Views: 680

Answers (1)

Louis Jacomet
Louis Jacomet

Reputation: 14500

Ehcache is a library designed for concurrent access and thus handles multi threading, concurrent mutations and related problems in the best possible way.

Now your understanding of the CacheLoaderWriter seems problematic. You are not supposed to access the cache from a CacheLoaderWriter instead the CacheLoaderWriter will be accessed by the cache when required, that is for the load* methods when a mapping is requested but not found in the cache.

However your CacheLoaderWriter implementation must be thread safe as Ehcache will use it concurrently. Also in your proposed implementation you are maintaining state inside the CacheLoaderWriter which is redundant with what the Cache will do ... if I understand correctly what you are trying to achieve.

Upvotes: 1

Related Questions