Reduce Memory Usage With WeakHashMap
Asked Answered
D

2

1

In the Javadoc of WeakHashMap.html, it said

"Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference. Therefore a key will automatically be removed only after the weak references to it, both inside and outside of the map, have been cleared by the garbage collector."

And then

Note that a value object may refer indirectly to its key via the WeakHashMap itself; that is, a value object may strongly refer to some other key object whose associated value object, in turn, strongly refers to the key of the first value object.

But should not both Key and Value should be used weak reference in WeakHashMap? i.e. if there is low on memory, GC will free the memory held by the value object (since the value object most likely take up more memory than key object in most cases)?

And if GC free the Value object, the Key Object can be free as well?

Basically, I am looking for a HashMap which will reduce memory usage when there is low memory (GC collects the value and key objects if necessary).

Is it possible in Java?

Thank you.

Diarthrosis answered 18/3, 2010 at 21:19 Comment(0)
T
1

Weak references are inappropriate for caches - NetBeans does it, and can go silly.

SoftReference is what you want. It's actually quite difficult to get it right - so copy somebody else's solution. Some people advise explicitly managing caches yourself.

References only work with a single reference. There was a proposal for adding "ephemerons" to Java SE, but I haven't seen an implementation go anywhere with that.

Tse answered 18/3, 2010 at 21:22 Comment(1)
I haven't heard good things about SoftReference so far. They wait until heap becomes scarce to be freed, that the performance suffers due to increased GC activity (well, maybe in your case it will work fine). You can also use something like LRU map. Ehcache is also a possible solution.Doordie
J
1

The idea is that you can use this Map as "lookup" data structure which only keeps the key-value-pairs alive which still can be referenced to (via a key). Still, while the basic idea is nice, I remember that it was not as useful as I hoped it would be.

Jeanajeanbaptiste answered 18/3, 2010 at 21:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.