Application Development, Product to Market
  • Home
  • Notes
  • Projects
  • Resources
    • Discovery Log
    • Books I Read
    • Blogs I Visit
    • Tools I Use
  • Home
  • Notes
  • Projects
  • Resources
    • Discovery Log
    • Books I Read
    • Blogs I Visit
    • Tools I Use

WeakHashMap Example

7/2/2013

0 Comments

 
Before I go into WeakHashmap, first let's look at different types of reference-object. A reference object encapsulates a reference to some other object. There are different level of reachability of references, from the strongest to the weakest. The weaker the reference, the more likely it is to be thrown away.
Strong Reference: In JVM, if an object is reachable via a chain of strong references (strongly reachable), it is not eligible for garbage collection. 

Soft Reference: A soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. Weakly reachable objects will be discarded at the next garbage collection cycle, but softly reachable objects will generally stick around for a while as long as memory is in plentiful supply. The nature of Soft Reference making it suitable for caching.

Weak Reference: A weak reference is a reference that isn't strong enough to force an object to remain in memory. When the underlying strong reference is gone, the weak reference will be discarded at the next garbage collection cycle.

Phantom Reference: The weakest referenced object which is only garbage collected once the phantom reference becomes unreachable itself. This reference is a signal that the object has already been finalized, and the garbage collector is ready to reclaim its memory. (see references) 

A WeakHashMap works just like a HashMap, except that the keys (not the values) are referred to using weak references. If a WeakHashMap key becomes garbage, its entry will be removed silently even though not necessarily immediately. With this nature, WeakHashMap is mostly useful to keep metadata about objects whose lifecycle you don't control. 

WeakHashMap is good for holding metadata about objects. In other words, you can associate some extra information to an object that you have a strong reference to. You put an entry in a WeakHashMap with the object as the key, and the extra information as the map value. 
Wouldn't it be nice when the object has no more strong reference, the metadata about the objects will be garbage collected silently? I use the following example to demonstrate the point of keeping track of metadata of existing objects. Let's say we want to have a map to hold meta information for every object that we track. The key is the object to be tracked, the value is its corresponding MetaInfo - say, registration time and counter. Applying a WeakHashMap is simple, just use a WeakHashMap in place of a HashMap in your code. As a result, when a key  in a WeakHashMap is no longer referenced elsewhere, the entry in the WeakHashMap will be removed silently.
public class MetaInfo{
  static Map metainfo = new WeakHashMap();      // 1

  long registrationTime;
  int counter = 0;

  public MetaInfo(){
    registrationTime = System.currentTimeMillis();
  }

  public static void registerObject(Object o){  // 2
    metainfo.put(o, new MetaInfo());
  }

  public static void incrementCount(Object o){
    ((MetaInfo) metainfo.get(o)).counter++;
  }

  public static int getCount(Object o){
    return ((MetaInfo) metainfo.get(o)).counter;
  }

  public static long getElapseTimeMillis(Object o){
    return System.currentTimeMillis() - ((MetaInfo) metainfo.get(o)).registrationTime;
  }
}

[1] The keys entered into a WeakHashMap are held using WeakReferences. This allows the garbage collector to collect the keys if there are no other strong references to those keys elsewhere in the application.
[2] A static function to put (or 'register', if you will) an object-MetaInfo pair into WeakHashMap. You don't have to unregister an object-MegaInfo as it'll be 'unregistered' soon after the key goes out-of-scope.

Using WeakHashMap comes with a price because every call to the WeakHashMap has one extra level of indirection it must go through to reach its underlying MashMap (e.g. WeakHashMap.get() calls HashMap.get()), which can be a significant performance overhead. Also, every call to get() creates a new WeakReference object to enable equality testing of keys in the internal HashMap. There's this slight performance hit you have to give up in exchange of better memory management. Also be noted that WeakHashMap is not meant as the data structure for caching.

references

  • WeakHashMap Javadoc
  • WeakHashMap Example on Stackoverflow
  • Soft, Weak, and PhantomReference?
  • Caching Data in Java and LRU strategy
  • Finalization and Phantom References
0 Comments



Leave a Reply.

    Categories

    All
    Algorithm
    Concurrency
    CQ
    Data Structure
    Design Pattern
    Developer Tool
    Dynamic Programming
    Entrepreneur
    Functional Programming
    IDE
    Java
    JMX
    Marketing
    Marklogic
    Memory
    OSGI
    Performance
    Product
    Product Management
    Security
    Services
    Sling
    Social Media Programming
    Software Development

    Feed Widget

    Archives

    May 2020
    March 2020
    April 2018
    March 2018
    February 2018
    December 2017
    March 2017
    November 2016
    June 2016
    May 2016
    April 2016
    October 2015
    September 2015
    August 2015
    September 2014
    July 2014
    June 2014
    May 2014
    March 2014
    January 2014
    December 2013
    November 2013
    October 2013
    September 2013
    August 2013
    July 2013
    June 2013

    RSS Feed

in loving memory of my mother  and my 4th aunt
Photos used under Creative Commons from net_efekt, schani, visnup, Dan Zen, gadl, bobbigmac, Susana López-Urrutia, jwalsh, Philippe Put, michael pollak, oskay, Creative Tools, Violentz, Kyknoord, mobilyazilar