1

I am trying to implement an in-memory cache.

The cache is populated during startup, the map inside the enum can be updated any time during the lifetime of the application.

What can be the impact of Garbage collection on this implementation? Since the enum is like a static class I am assuming that only one instance of the map object is created and contents of this map are not garbage collected.

We have seen that sometimes keys from this map go missing can this be because of GC?

We are returning a new map whenever a call is made to retrieve this cache

public enum  EmployeeCache {
        INSTANCE;
        private Map<String,Map<String, Employee>> employeeCacheMap = new ConcurrentHashMap<>();
    
        public void populateEmployeeCache(String tenantId,Map<String, Employee> inputEmployeeCacheMap){
            Map<String, Employee> localEmployeeCacheMap = new ConcurrentHashMap<>(inputEmployeeCacheMap);
            employeeCacheMap.put(tenantId,localEmployeeCacheMap);
        }
    
        public Map<String, Employee> getEmployeeCacheMap(String tenantId){
            Map<String,Employee> localMap = new HashMap<>();
            if(employeeCacheMap.get(tenantId) != null) {
                localMap.putAll(employeeCacheMap.get(tenantId));
            }
            return localMap;
        }
    
        public Employee getEmployeeInfo(String tenantId,String Employee){
            return employeeCacheMap.get(tenantId).get(Employee);
        }
    }
unnik
  • 1,123
  • 5
  • 18
  • 37
  • So why not make a Singleton class and store the cache in it? –  Oct 20 '20 at 17:48
  • This is an Enum based singleton class. https://stackoverflow.com/questions/26285520/implementing-singleton-with-an-enum-in-java – unnik Oct 21 '20 at 02:43
  • from what I've looked at the code you have race. `ThreadA` calls `getEmployeeInfo`, does `employeeCacheMap.get(tenantId)`, but not _yet_ `get(Employee)`. `ThreadB` calls `populateEmployeeCache` with the same `tenantId` and updates the Map. `ThreadA` does `get(Employee)` on a `Map` that has already changed. having nested `ConcurrentHashMap`s does not make your code thread-safe immediately. – Eugene Oct 21 '20 at 03:22
  • Yes. I agree there can be inconsistency, but not sure how can keys be deleted from the map. – unnik Oct 21 '20 at 04:44
  • 2
    @unnik first of all, fix the thread safety, this might be the cause of your problems. – Eugene Oct 21 '20 at 11:22
  • You have synchronisation problems all over the place. Add `synchronised` to all your methods and see if the problem goes away. Also, I don't quite understand the need for the `getEmployeeCacheMap` method. – Erik Oct 22 '20 at 07:03
  • To get all the entries from the map – unnik Oct 22 '20 at 15:04

0 Answers0