WeakHashMap vs HashMap

Discussion in 'Java' started by iksrazal, Feb 10, 2004.

  1. iksrazal

    iksrazal Guest

    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
    iksrazal, Feb 10, 2004
    #1
    1. Advertising

  2. iksrazal

    Adam Guest

    "iksrazal" <> wrote in message
    news:...
    > 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
    Adam, Feb 11, 2004
    #2
    1. Advertising

  3. iksrazal

    xarax Guest

    "Adam" <> wrote in message
    news:c0co09$hn1$...
    >
    > "iksrazal" <> wrote in message
    > news:...
    > > 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


    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!
    xarax, Feb 11, 2004
    #3
  4. iksrazal

    Chris Smith Guest

    Adam wrote:
    > 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
    Chris Smith, Feb 11, 2004
    #4
  5. iksrazal

    Adam Guest

    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
    Adam, Feb 12, 2004
    #5
  6. iksrazal

    dearmayank

    Joined:
    Dec 23, 2010
    Messages:
    1
    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
    dearmayank, Dec 23, 2010
    #6
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. mitch gart

    WeakHashMap question

    mitch gart, Nov 17, 2003, in forum: Java
    Replies:
    2
    Views:
    1,122
    Adam Jenkins
    Dec 1, 2003
  2. Abs

    WeakHashMap

    Abs, Jun 13, 2004, in forum: Java
    Replies:
    6
    Views:
    874
  3. Vince Darley
    Replies:
    4
    Views:
    4,391
    emilchacko
    Mar 2, 2010
  4. Hendrik Maryns

    WeakHashMap for values

    Hendrik Maryns, Jun 8, 2006, in forum: Java
    Replies:
    3
    Views:
    1,269
    Hendrik Maryns
    Jun 8, 2006
  5. Rakesh
    Replies:
    10
    Views:
    12,151
    Mike Schilling
    Apr 8, 2008
Loading...

Share This Page