File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Data structure to cache objects

 
Humberto Hernandez
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
David Harrigan
Ranch Hand
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't know if it's a good solution, but why not have another collection (ArrayList perhaps) that takes the Object Id as the key and a simple counter that is incremented whenever an object is referenced. You can then have another thread that is launched at specific times, examines the value for each entry in the collection and if is below a certain access threshold (say 50) then it removes that object from the HashMap???
David.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic