• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Data structure to cache objects

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic