This is a
pattern we frecuently use.
public class MyObject {
private MyObject(
String id) {
// Load from the database.
// This is a heavy operation.
}
private static HashMap cache = new HashMap();
public static MyObject getMyObject(String id) {
// Avoid creating the objects every time if you can.
MyObject obj = (MyObject)cache.get(id);
if (obj == null) {
// Object is not cached, so you have to create it.
obj = new MyObject(id);
cache.put(id, obj);
}
return obj;
}
}
This works fine, but eventually will get all the objects in memory. I will like to be able keep the cache at a fixed size
and replace the least recently used objects. For that I think I need a complementary data structure to keep a list of the most recently used objects.
Has anyone done something similar or has any design suggestions
for this problem?