WeakHashMap - ayushmathur94/DirectQuesAns_Prep GitHub Wiki

For understanding this , first we have to understand What are weak references , strong references and soft references ?

Strong References

By default any object in Java has a strong reference ie. it will be garbage collected only if there are no references to it.

private static void strongReference(){
Employee emp = new Employee(1441,"KK");   // strong reference 
emp = null;     // emp becomes Eligible for Garbage Collection
}

Weak References

A weak reference is a reference that isn't strong enough to force an object to remain in memory. Using a weak reference , we can simply rely on the garbage collector's ability to determine the reachability of an object on the heap.

WeakReference weakWidget = new WeakReference(widget);

In the code you can use weakWidget.get() to get the actual Widget object. Of course the weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) that weakWidget.get() suddenly starts returning null.

private static void weakReferenceEg(){
Employee emp = new Employee(1441, "KK");
WeakReference< Employee >  weakReference = new WeakReference< Employee > (emp); 
System.out.println(weakReference.get());
emp = null;
System.gc();
System.out.println(weakReference.get());
}

 output : 
Employee [id=1441, name=kk]
null

Soft Reference

Soft Reference is very similar to the weak reference except that it will be cleared or garbage collected only when there are any memory issues like running out of memory. The garbage collector will reclaim all the soft reference objects before it throws out of memory error. GC will try its best by clearing all the soft reference objects , will try to reclaim the memory , but even then if the memory isn't sufficient then it will throw out of memory error.

SoftReference< Employee > softReference = new SoftReference< Employee >(); 

A good example for using soft reference is to implement our own caching strategy. If we use soft references, the objects cached will stay in memory until we have some memory issues and just before the garbage collector or JVM throws out of memory error , it will clear our cache and see that the memory issues are resolved.

WeakHashMap

A weakhashmap is a good example which uses weak references to its keys. If a weakhashmap is used , the objects will be removed as soon as they are no longer used by any other objects in our application. Although the HashMap itself might be having the key-value pair and pointing to it, since the key itself is a weak reference if anything outside the hashmap is not using it , that entire key-value pair will be deleted from the hashmap.

⚠️ **GitHub.com Fallback** ⚠️