• Post Reply Bookmark Topic Watch Topic
  • New Topic

Timed HashMap  RSS feed

 
Alan Mc Kernan
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a hashmap, which i use in a reader/writer fashion. But sometimes the readers dont come along and take the object out(theres nothing we can do about this). This is causing a memory leak. Any idea's on some kind of HashMap with a timeout period, where the stale objects will be removed?

Any ideas appreciated,
Alan
 
Ray Stojonic
Ranch Hand
Posts: 326
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Extend HashMap as TimedHashMap
Incorporate a Timer, start Timer on instantiation.
Override put() to wrap inbound Objects in a TimedObject
Override get() to unwrap Objects
When Timer fires, clear out old TimedObjects

TimedObject has a timestamp, set on instantiation, and a variable to hold an Object
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That would likely work, but extending any concrete class can get you in trouble with the Liskov Substitution Principle and long term maintenance. It would be safer (and more effort, and some additional overhead) to provide a new class that implements a get() and put() interface and happens to use a HashMap inside.

See Extends is Evil. I think Holub is deliberately provocative and over the top, but there are some nuggets in there.
 
Ray Stojonic
Ranch Hand
Posts: 326
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm anything but an LSP expert, but I think adding a TimedHashMap( long maxAge ) constructor and having the default constructor not even start the Timer would make this agree with LSP. Other than that, Objects in and Objects out, just like HashMap. (the contents of toString and the result of containsValue are the stored Object's (in this case: TimedObject) responsibility)

I'm curious about the long-term maintenance problems, can you go into that a bit?

Would implementing Map and wrapping a HashMap be preferable?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!