EdgeCase
EdgeCase

Reputation: 4827

Static Cache - Two "Instances"

I have an application where I need two static caches, once short-term and one long-term.

So I have an abstract class that looks something like this. My thought was that I would create two classes that inherit from this abstract class, thereby attaining my two static classes.

However, it occurs to me that I am creating 3 objects when I might be able to get by with one. But I am at a loss in how to do so. Do I want some sort of factory class?

Can someone suggest an appropriate pattern here?

public abstract class myCache {
    static Map<String, Object> ObjectCache = new ConcurrentHashMap<String, Object>();

    public void put(String Key, T cmsObject) {
    //
    }

      public xxx static get(String objectKey, Class<T> type) {
    //
    }
}

Upvotes: 0

Views: 1276

Answers (2)

chenjw
chenjw

Reputation: 11

public abstract class myCache {

    static ConcurrentMap<Class<?>,Map<String, Object>> ObjectCache = new ConcurrentHashMap<Class<?>,Map<String, Object>>();

    {
         ObjectCache.putIfAbsent(getClass(),new ConcurrentHashMap<String,Object>());
    }

    public void put(String Key, Object cmsObject) {
         ObjectCache.get(this.getClass()).put(key,cmsObject);
    }

    public Object get(String objectKey) {
         return ObjectCache.get(this.getClass()).get(key);
    }
}

Upvotes: 1

Bohemian
Bohemian

Reputation: 425043

Your design is flawed:

  • A cache is a cache - let the caching class take care of caching... only
  • Unless the number of objects is large (1000's), don't let the "number of objects created" influence your design
  • Only the user of your cache class needs to know or care what how the cache is being used

Thus:

public class MyClass {

    private static MyCache shortTermCache = new MyCache();
    private static MyCache longTermCache = new MyCache();

}

You may consider passing a time-to-live parameter into your cache class constructor to let it manage purging after a certain time.

Upvotes: 1

Related Questions