Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

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.
 
I was born with webbed fish toes. This tiny ad is my only friend:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic