? Design Pattern to cache service calls?

T

timasmith

I have a fat client application which looks up fairly static reference
data (database table)

Example - columns to display for a search result list

I have the following code below as a snippet to cache the results while
the application is running - restarting the app clears the cache.

However it looks fragile and relies on the developer not making a
mistake when assigning the key for the cached service call

Is there a design pattern best suited for this common issue?

private static Hashtable cache = new Hashtable();

public static AppColumnList getSearchColumns(int applicationId) {
String key = applicationId + ":ServiceClass:getSearchColumns";
if (cache.containsKey(key)) {
AppColumnList value = (AppColumnList) cache.get(key);
return value;
} else {
AppColumnList value = getService().getAppColumns(applicationId,
userid);
cache.put(key,value);
return value;
}
}
 
T

Timo Stamm

I have a fat client application which looks up fairly static reference
data (database table)

Example - columns to display for a search result list

I have the following code below as a snippet to cache the results while
the application is running - restarting the app clears the cache.

However it looks fragile and relies on the developer not making a
mistake when assigning the key for the cached service call

I don't know what you mean. You always need a compact key for cache lookup.

There are several ways to implement memory caches in java. A more
advanced on might use weak references to use as much as possible (but
not more).

Is there a design pattern best suited for this common issue?

private static Hashtable cache = new Hashtable();

public static AppColumnList getSearchColumns(int applicationId) {
String key = applicationId + ":ServiceClass:getSearchColumns";
if (cache.containsKey(key)) {
AppColumnList value = (AppColumnList) cache.get(key);
return value;
} else {
AppColumnList value = getService().getAppColumns(applicationId,
userid);
cache.put(key,value);
return value;
}
}

You never remove data from the cache?


The LinkedHashMap has a nice feature: It can remove its eldest entry:


class MemCache extends LinkedHashMap<String, byte[]> {

private int e;

public MemCache(int entries) {
super(entries, 0.75f, true);
e = entries;
}
@Override
protected boolean removeEldestEntry(Entry<Object, byte[]> arg0) {
return size() > e;
}
}


Timo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top