Thursday, October 21, 2021

How to use WeakHashMap in Java? Example Tutorial

Hello friends, we are here today again on our journey to Java. I hope everyone is fine and ready to board our train of knowledge. Today we are gonna learn something very interesting and very exciting. Today's topic will definitely be very useful in coding and programming. This topic would surely decrease your time complexity, and space requirements for any task very significantly :p So what's the wait? Let's start!

As always, we will start understanding today's topic by a scenario. But, before that, you guys must know what a HashMap is. So, go through the HashMap article before jumping on this one, and you will get a better understanding of today's article. For the guys who have already gone through HashMap before, let me give a brief intro and what a HashMap is so we all can refresh the topic easily.


1. HashMap:

The Java HashMap implementation of the Map interface is based on hash tables. A Map is a set of key-value pairs, as you may know. It converts keys into values.
  • There can't be any duplicate keys in a HashMap.
  • Null values and the null keys are allowed in Java HashMap.
  • HashMap is a collection that is not in any particular order. It does not ensure that the elements will be in any certain sequence.
  • HashMap in Java is not thread-safe. You must explicitly synchronize concurrent HashMap changes.

HashMap is declared as:

Map<String, Integer> map = new HashMap<>();


Now, after you guys know what HashMap is, let's jump into today's topic with a scenario.



Let's say we have a HashMap with us. 

The HashMap has a String key type and the value type is Integer. Let's say we have unique car names as key and value is the max speed limit of the cars.

So, the HashMap would look like this:
Map<String,Integer> carMap = new HashMap<>();

The values inside the map would be similar to this: {'BMW m3' - 360, 'Audi a6 - 340', 'Mercedes q3 - 320', 'Bugatti Veyron - 420'}. This represents the {'key' - value} notation. Each key is linked to its value. Now, suppose this list grows on and the records are now in millions! 

This would end up consuming all our space and we would get a StackOverflowError anytime! For obvious reasons, we don't want that. So, let's see how out today's topic is relevant to it and then you guys can yourself take care of the solution to the above problem.




2. WeakHashMap:

WeakHashMap is a Map interface implementation that only holds weak references to its keys. When a key-value pair is only stored as weak references, it may be garbage-collected when its key is no longer referenced outside of the WeakHashMap.

This class makes it simple to take advantage of the power of weak references. It's helpful for creating "registry-like" data structures, in which an entry's utility disappears when its key is no longer accessible by any thread.

The WeakHashMap is similar to the HashMap except for one crucial difference: if the Java memory manager no longer holds a strong reference to the object given as a key, the item in the map is deleted.




Also, the Javadocs gave an explicit implementation note for WeakHashMap.In a WeakHashMap, the value objects are kept by regular strong references. As a result, value objects should be careful not to make strong references to their own keys, either directly or indirectly, as this will prevent the keys from being destroyed. 

It's worth noting that a value object can indirectly refer to its key through the WeakHashMap; that is, a value object can strongly refer to another key object, whose associated value object, in turn, strongly refers to the key of the first value object. 

If the values in the map do not rely on the map having strong references to them, wrapping the values in WeakReferences before inserting is one solution.





3. How to use WeakAShMap in Java? Coding Example

Now that you guys have an understanding of what a WeakHashMap is, let's see its code and how it is implemented.



import java.util.Map;
import java.util.WeakHashMap;

public class MyMap {
public static void main(String[] args) {
Map<String, Integer> map = new WeakHashMap<>();
map.put("Student1", 1);
map.put("Tom Cruise", 3);
map.put("Bond, James Bond", 7);
map.put("Selmon Bhoi", 0);
map.put(null, 9);


System.out.println("getting values from map now...");

System.out.println(map.get("Selmon Bhoi"));
System.out.println(map.get("Tom Cruise"));
System.out.println(map.get(null));

}
}

              

Output:



Now, you guys must be wondering that this is same as HashMap. What is the difference? The difference we cannot observe here because it is a very small program. The System will not garbage collect as there is plenty of memory available.

But, in scenarios of memory shortage, system will garbage collect the unused keys. You guys can try out with hands-on for this and using system.gc() which calls the garbage collection utility. Still, there's no guarantee that garbage collection will be performed by system.


Now, you guys will be thinking that when to use WeakHashMap. The garbage collector can recover elements in a weak hashmap if there are no other strong references to the key object; this makes them handy for caches and lookup storage.

Weak references aren't just for hash tables; they may also be used for single objects. They're helpful for conserving resources since they enable you to maintain a reference to something while allowing it to be collected when no one else refers to it. 

By the way, a strong reference is just a regular Java reference.) Weak references are less easily gathered than soft references (which don't tend to stick around for long after the last strong reference has vanished).


Hope you guys have enjoyed today's article. until next article, peace :p

Related Java HashMap tutorials  you may like
  • How does get() method of HashMap work in Java? (answer)
  • What is the difference between HashMap and Hashtable in Java? (answer)
  • What is the difference between ArrayList and HashMap in Java? (answer)
  • What is the difference between HashSet and HashMap in Java? (answer)
  • Difference between ConcurrentHashMap and HashMap in Java? (answer)
  • How HashSet internally works in Java? (answer)
  • How ConcurrentHashMap internally works in Java? (answer)
  • The difference between HashMap and LinkedHashMap in Java? (answer)
  • The best way to iterate over HashMap in Java? (answer)
  • How to sort the HashMap on keys and values in Java? (solution)
  • 3 ways to loop over a Map in Java? (example)
  • The difference between HashMap and ConcurrentHashMap in Java? (answer)
  • What is the difference between ArrayList and HashMap? (difference)
  • How to convert Map to List in Java? (solution)

Thanks for reading this article so far. If you liek this HashMap article then please share with your friends and colleages. If you have any questions or feedback, please ask in comments. 

P. S. - If you are new to Java and want to learn core Java in depth, you can also checkout these 10 Free Core Java Courses to staart with. It contains best free Java courses from Udemy and Coursera for beginners. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.