WeakHashMap vs HashMap

I

iksrazal

Could someone please explain why one would choose WeakHashMap over
Hashmap? It seesms to have something to do with garbage collection and
references, which is confusing me. It also seems common to have a
'WeakHashMap of WeakHashMaps', such as for xml parsing. What's the
advantage of all this?

iksrazal
 
A

Adam

iksrazal said:
Could someone please explain why one would choose WeakHashMap over
Hashmap? It seesms to have something to do with garbage collection and
references, which is confusing me.

People use it to implement 'cache memory'.
If you have some objects that are reused
often in your application, and their
construction is expensive, and there
are too many of them to keep them all
in memory -
- you use WeakHashMap.

Put there the object which is not currently
used. When this object is needed - get it out
of the map. For most of the time most of those
objects will be staying in the map.
The trick is that they are not held
directly, but through WeakReferences.
So if it gets really 'crowded', when we are running
out of memory, gc will be allowed to collect
them.
So every time you try to get the object out of
the WeakHashMap, you have to ensure it
is still there. Otherwise you need to
recreate it.

HTH,
Adam
 
X

xarax

Adam said:
People use it to implement 'cache memory'.
If you have some objects that are reused
often in your application, and their
construction is expensive, and there
are too many of them to keep them all
in memory -
- you use WeakHashMap.

Put there the object which is not currently
used. When this object is needed - get it out
of the map. For most of the time most of those
objects will be staying in the map.
The trick is that they are not held
directly, but through WeakReferences.
So if it gets really 'crowded', when we are running
out of memory, gc will be allowed to collect
them.
So every time you try to get the object out of
the WeakHashMap, you have to ensure it
is still there. Otherwise you need to
recreate it.

HTH,
Adam

That's not what WeakHashMap does. Only the KEYS
are WeakReference objects, not the values that
are mapped by the keys. Be sure that the key
objects are not "permanently resident" objects,
like hard-coded String instances, because a
WeakHashMap only consolidates evaporated keys
when the garbage collector reclaims the key object.
That cannot happen for permanently resident objects.

If you want the values (as opposed to keys) to
evaporate over time, then you must wrap those values
with SoftReference or WeakReference wrappers, and then
be *absolutely* certain that you have nulled all other
references.

The value wrapped by a SoftReference wrapper is not
cleared until some time after: The last strong reference
for the value becomes unreachable by all live threads.
Another way of saying that is the value is only softly
reachable and not strongly reachable.

The value wrapped by a WeakReference wrapper is not
cleared until some time after: The last strong reference
for the value becomes unreachable by all live threads
*and* there are no SoftReference objects referring to
the value. The value is not strongly reachable and not
softly reachable.

The various JVM may implement garbage collection
in different ways and provide support for Reference
objects in different ways. Read the JavaDoc for the
java.lang.ref.Reference class and friends for details
about interactions with the garbage collector.

--
----------------------------
Jeffrey D. Smith
Farsight Systems Corporation
24 BURLINGTON DRIVE
LONGMONT, CO 80501-6906
http://www.farsight-systems.com
z/Debug debugs your Systems/C programs running on IBM z/OS!
Are ISV upgrade fees too high? Check our custom product development!
 
C

Chris Smith

Adam said:
People use it to implement 'cache memory'.
If you have some objects that are reused
often in your application, and their
construction is expensive, and there
are too many of them to keep them all
in memory -
- you use WeakHashMap.

Put there the object which is not currently
used. When this object is needed - get it out
of the map. For most of the time most of those
objects will be staying in the map.
The trick is that they are not held
directly, but through WeakReferences.
So if it gets really 'crowded', when we are running
out of memory, gc will be allowed to collect
them.

This isn't really accurate. WeakHashMap uses WeakReference, not
SoftReference, for one thing. That means the garbage collector will
make no more effort to keep objects in memory than it would have made if
there were no references to them at all. Second, and most importantly,
it's the *keys* that are kept with weak references; the objects are
considered strongly referenced until the key becomes unreachable.

I have no idea why there's no SoftHashMap class in the Java core API
that acts as Adam wrote above. It would make sense to have around, and
I've written at least one of them. Nevertheless, they are a different
and unrelated matter.

The purpose of WeakHashMap is to provide a Map implementation that will
automatically discard objects when it's impossible to get them back out
again. As such, it must be used in situations where two objects can't
be considered equal unless they really are the same object.

As an example, I could have an application that receives task
descriptions and performs some long-term operations on their behalf.
Let's say, just for kicks, that I'm going to spawn separate threads for
each of these operations and then let them do their work, while the
first thread goes on to wait for more task descriptions. The important
bit about this architecture is that there is no single point where you
can clean up after a task; when any of the parallel threads finishes, it
may or may not be the last thread performing work for that task, and
there's no easy way to find out.

Now, let's suppose that the tasks are related enough that there are some
expensive shared computations between them. The results of these
computations, though, are valid only within that task. And let's say
we've chosen to store those computations in a global synchronized Map.
The question is this: when do we remove these cached computations from
the global Map.

WeakHashMap gives an answer: if we use some object with a unique
identity (meaning, in a nutshell, that it doesn't override the equals
method) as a key for the computations; and if that key is passed along
and shared by all the threads in a given task but never communicated
outside of the task, then as soon as all the threads exit, the key will
become unreachable (Because the WeakHashMap holds only a weak
reference). When the garbage collector realizes that the key is
unreachable, the WeakHashMap will automatically remove those
computations from the cache.

There's a use for WeakHashMap. In all honesty, though, I think there
are better designs (task-specific HashMap, for example), and I have a
hard time justifying a situation that really requires a WeakHashMap to
implement reasonably. Nevertheless, that's up to each individual
developer to decide for their own projects.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
A

Adam

Thanks for pointing my 'inaccuracy' Chris and xarax.
Well, as it shows, it is always worth focusing and concentrating
on what you are reading (which I didn't when
I was skimming the WeakHashMap javadocs :))

Adam
 
Joined
Dec 23, 2010
Messages
1
Reaction score
0
WeakHashMap with diff in SoftReferences and WeakReferences

Hi Friends,

Just got a realy good explanation so thought of sharing it:

WeakReferences are cleared agressively; SoftReferences are not. Using a SoftReference tells the garbage collector that you would like it to keep the object around for a while, until memory considerations cause it to reclaim the object. By contrast, using a WeakReference tells the garbage collector that there's no reason to keep the object around any longer than necessary.
SoftReferences are primarily for implementing memory-senstive caches. WeakReferences are primarily for associating extra information with an object (that's what WeakHashMap does).

What is WeakHashMap for?
It's not for caching. The idea is, suppose you have a bunch of objects of a certain class that you can't extend, but you want to associate some other piece of information with each object. You can use a Map, with the main object as the key and the extra info as the value. Using a WeakHashMap for this will make sure that your Map won't cause a memory leak, because it won't hold a strong reference to the main (key) object; this will allow the object to be garbage collected when it's no longer needed. I believe that when the key is garbage collected, the value will soon be garbage collected too, though not immediately.


Cheers,
Mayank
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top