Java WeakHashMap Working Examples


A quick practical guide to java WeakHashMap in java.util package. It is based on Hashtable and if any key is not in use that automatically removed from WeakHashMap. Demo on WeakHashMap working example.

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);
value = null;

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());
System.out.println("After gc run weakHashMap size : " + weakHashMap.size());


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:


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:


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");

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.



About Us

Author: Venkatesh - I love to learn and share the technical stuff.

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,2,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,20,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,73,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,48,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,3,Streams,11,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,8,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
JavaProgramTo.com: Java WeakHashMap Working Examples
Java WeakHashMap Working Examples
A quick practical guide to java WeakHashMap in java.util package. It is based on Hashtable and if any key is not in use that automatically removed from WeakHashMap. Demo on WeakHashMap working example.
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content