This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes Data structure to cache objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Data structure to cache objects" Watch "Data structure to cache objects" New topic
Author

Data structure to cache objects

Humberto Hernandez
Greenhorn

Joined: Nov 01, 2000
Posts: 13
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

Joined: Dec 12, 2000
Posts: 52
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.
 
Don't get me started about those stupid light bulbs.
 
subject: Data structure to cache objects
 
Similar Threads
Static object
XMLEncoder - Stackoverflowerror - overriding equals
Using static
Design Question - Refreshing Singletons
Cache Implementaion