Pages

Wednesday, January 15, 2020

Java WeakHashMap Working Examples

1. Overview


In this tutorial, We'll be talking about WeakHashMap in java and it is placed in java.util package.

WeakHashMap is implemented based on Hashtable with weak keys. Map internally is built on Entry objects. When adding a key-value pair, it will be stored in the Entry object. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. So, once the key is deleted from the map it is eligible for Garbage Collection and we can not prevent from running GC on it. This class completely behaves differently than other Map implementations such as HashMap, LinkedHashMap, etc. And also it has efficiency parameters of initial capacity and load factor as same as HashMap.

Java WeakHashMap Working Examples


AbstractMap is the superclass for WeakHashMap and it implements Map interface. So, it acquires all its default methods. WeakHashMap is designed to store null values as key and value.

We should understand the basic terms Strong reference, Soft Reference, and Weak Reference.

Next in this article, We will see example programs on each method of this class.



2. Strong reference, Soft Reference, and Weak Reference


To understand in a better way on WeakHashMap, we should know about Strong reference, Soft Reference, and Weak Reference. Because the key is stored in WeakReference which is inherited by Entry class in WeakHashMap.

private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> 

2.1 Strong Reference


Strong Reference is the one we use regularly by every java developer. That means variable points to some value.

double PI = 3.14;

Here PI value is assigned with 3.14 which is saying variable PI has a reference to value always. This is called Strong Reference.

2.2 Soft Reference


Java api has a class SoftReference which holds the value but releases when GC needs memory.

All soft references to softly-reachable objects are guaranteed to have been cleared before the virtual machine throws an OutOfMemoryError.

Double PI = 3.14;
SoftReference<Double> reference = new SoftReference<Double>(PI);
PI = null;

2.3 Weak Reference


WeakReference is a class in java and when a value is added to that GC will be executed immediately if really memory is needed.

String value = "WeakReference";
WeakReference<String> weakReference = new WeakReference<String>(value);
Thread.sleep(5000);
value = null;
System.out.println(value);

This string value will be garbage collected when GC runs in the next cycle.


3. WeakHashMap Example as an Efficient Memory Cache


If we want to store huge data in key-value pair then we shuold consider the WeakHashMap incase it needs to cleared after certain usage. If we use normal HashMap then it will consume lots of memory and will not be claimed by GC even after usage completion. Even they are not used by application but still blocks the memory. This may cause to OutOfMemoryError.

Basically, We need a optimized cache technique to use map memory effectively. When a key-value pair is not in usage then that memory should freed up by GC automatically. Such type characteristic Map implementation is done by WeakhashMap.

Map<Integer, String> weakHashMap = new WeakHashMap<>();

IntStream.range(0, 1000).forEach(i -> weakHashMap.put(i, Integer.toString(i)));
System.out.println("before gc run weakHashMap size : " + weakHashMap.size());
Runtime.getRuntime().gc();
Thread.sleep(5000);
System.out.println("After gc run weakHashMap size : " + weakHashMap.size());

Output:

before gc run weakHashMap size : 1000
After gc run weakHashMap size : 128

All 1000 key/value pairs are added to WeakReference. But not used by any threads. So, whichever is not in usage, GC will find all weak references and clear the momory.

Like most collection classes, this class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.synchronizedMap method.

4. WeakHashMap clear() Example


Removes all of the mappings from this map. The map will be empty after this call returns.

clear Syntax:

public void clear()

clear Example:

weakHashMap.clear();

After calling clear() method size if the map will be 0.

5. WeakHashMap containsKey() Example


Returns true if this map contains a mapping for the specified key.

containsKey Syntax:

public boolean containsKey(Object key)


containsKey Example:

System.out.println(weakHashMap.containsKey(999));

This line prints true.

6. WeakHashMap size() Example


Returns the number of key-value mappings in this map. This result is a snapshot, and may not reflect unprocessed entries that will be removed before next attempted access because they are no longer referenced.

size() Syntax:

public int size()

size() Example:

int size = weakHashMap.size();

size can be some value and this value can not be predicted.

7. WeakHashMap isEmpty() Example


Returns true if this map contains no key-value mappings. This result is a snapshot, and may not reflect unprocessed entries that will be removed before next attempted access because they are no longer referenced.

isEmpty syntax:

public boolean isEmpty()


isEmpty Example:

boolean isEmpty = weakHashMap.isEmpty();

This isEmpty will be empty if all are prcocessed by GC.

8. WeakHashMap get() and put() Example


get(): Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

get Syntax:

public V get(Object key)

put(): Associates the specified value with the specified key in this map. If the map previously contained a mapping for this key, the old value is replaced.

put Syntax:


public V put(K key, V value)

get() and put() examples:

weakHashMap.put(10000, "10000");
System.out.println(weakHashMap.get(10000));

9. Conclusion


In this post, We have seen what are the types of referenes allowed in java and how java.util.WeakHashMap works.

And, also seen all methods with working examples on each.

The code shown in this tutorial is over GitHub.
API Ref




No comments:

Post a Comment

Please do not add any spam links in the comments section.