C

Core Java tutorial for beginners

Clean • Professional

WeakHashMap in Java – Working, Garbage Collection, Examples & Use Cases

4 minute

WeakHashMap in Java

WeakHashMap is a special Map implementation in Java where the keys are stored as weak references. This means if a key is no longer strongly referenced elsewhere, it can be garbage collected, and its entry is automatically removed from the map.

It is part of the java.util package.


What is WeakHashMap?

  • A hash table-based Map implementation.
  • Keys are weakly referenced; values are strongly referenced.
  • Automatically removes entries when a key is no longer in ordinary use.
  • Useful for memory-sensitive caching, metadata storage, and canonical mappings.

Package

import java.util.WeakHashMap;

Key Features

  • Keys are weakly referenced → garbage collection removes entries automatically.
  • Values are strongly referenced.
  • Allows null keys and null values.
  • Not synchronized → use Collections.synchronizedMap() for thread safety.
  • Iterators are fail-fast.
  • Implements Map<K, V>, Cloneable, and Serializable.

Collection Hierarchy

Iterable
   └── Collection
          └── Map
                └── WeakHashMap

Internal Working

  • Keys are wrapped in WeakReference objects.
  • Values are stored normally.
  • When a key has no strong references, GC collects it → entry removed automatically.
  • Uses a ReferenceQueue internally to track garbage-collected keys.

Internal Diagram (Example)

Key (WeakRef) → Value
A (weak) → 10
B (weak) → 20
C (weak) → 30
  • If A is no longer referenced elsewhere, GC removes it → entry gone from map.

Constructors

Default Constructor

Creates an empty WeakHashMap with default capacity (16) and load factor (0.75).

WeakHashMap<K, V> map = new WeakHashMap<>();

With Initial Capacity

Creates a WeakHashMap with the given starting capacity to reduce early resizing.

WeakHashMap<K, V> map = new WeakHashMap<>(32);

With Initial Capacity & Load Factor

Creates a map with full control over initial capacity and load factor for performance tuning.

WeakHashMap<K, V> map = new WeakHashMap<>(32, 0.75f);

From Another Map

Creates a WeakHashMap by copying all entries from an existing map, converting the keys to weak references.

Map<K, V> existingMap = new HashMap<>();
WeakHashMap<K, V> map2 = new WeakHashMap<>(existingMap);

WeakHashMap Common Methods

learn code with durgesh images

MethodDescription
put(K key, V value)Adds or updates a key-value pair (key stored as a weak reference).
get(Object key)Returns the value for the given key, or null if not found or garbage-collected.
remove(Object key)Removes the mapping for the given key.
containsKey(Object key)Checks if the map contains the given key (if not garbage-collected).
containsValue(Object value)Checks if the map contains the given value.
size()Returns the number of active entries (expired weak keys are automatically removed).
isEmpty()Checks if the map has no valid entries.
keySet() / values() / entrySet()Returns views of keys, values, or entries.
clear()Removes all entries from the map.
putAll(Map m)Copies all entries from another map.

Note: When a key is garbage collected, its entry is automatically removed.


Example

import java.util.WeakHashMap;

public class Main {
    public static void main(String[] args) {
        WeakHashMap<String, String> map = new WeakHashMap<>();

        String key1 = new String("A");
        String key2 = new String("B");

        map.put(key1, "Apple");
        map.put(key2, "Banana");

        System.out.println("Before GC: " + map);

        key1 = null;  // key1 no longer strongly referenced
        System.gc();  // suggest garbage collection

        try { Thread.sleep(1000); } catch (InterruptedException e) {}

        System.out.println("After GC: " + map);
    }
}

Possible Output:

Before GC: {A=Apple, B=Banana}
After GC: {B=Banana}

Time Complexity

OperationAverage
put()O(1)
get()O(1)
remove()O(1)
containsKey()O(1)
iterationO(n)

WeakHashMap vs HashMap

FeatureHashMapWeakHashMap
Key ReferenceStrong referencesWeak references
Garbage CollectionKeys are never garbage collected automaticallyKeys are automatically removed when no strong reference exists
Null KeysAllows 1 null keyAllows 1 null key
Null ValuesAllows multiple null valuesAllows multiple null values
Thread-SafetyNot thread-safeNot thread-safe (wrap with Collections.synchronizedMap() if needed)
IterationFail-fastFail-fast
Use CaseGeneral-purpose mapMemory-sensitive caches, temporary mappings, canonicalizing objects
Memory ManagementKeys remain until explicitly removedHelps avoid memory leaks for keys no longer in use
PerformanceFast, standard hash-based operationsSimilar to HashMap, but additional overhead for weak references and reference queue handling

When to Use WeakHashMap

  • Caching objects that can be recreated if lost
  • Memory-sensitive applications
  • Storing canonical mappings or metadata
  • Avoid memory leaks for temporary keys

Advantages

  • Automatic cleanup of unused keys
  • Saves memory
  • Fast access (hash table)
  • Supports standard Map interface

Disadvantages

  • Not synchronized → needs wrapper for multi-threading
  • Values are not garbage collected automatically
  • Iterators are fail-fast → can throw ConcurrentModificationException
  • Behavior depends on GC → removal may not be immediate

Points to Remember

  • WeakHashMap = HashMap with weakly referenced keys
  • Keys get garbage collected automatically if not referenced elsewhere
  • Ideal for caching, canonicalization, and memory-sensitive scenarios
  • Iterators are fail-fast
  • Not thread-safe → use Collections.synchronizedMap() if needed

Article 0 of 0