Reputation: 4827
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
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
Reputation: 425043
Your design is flawed:
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