Skip to content

Java WeakHashMap

WeakHashMap—a powerful tool for managing memory efficiently. think of it as a special type of map in Java that allows you to associate keys with values, just like a regular HashMap. However, WeakHashMap has a unique feature—it holds weak references to its keys, making it particularly useful for scenarios where you want to avoid memory leaks.

Imagine you're hosting a magical tea party, and you've invited some guests. Each guest is represented by a key in your WeakHashMap, and their magical powers are the values associated with them. However, if a guest decides to leave the party (i.e., their reference is no longer strong), WeakHashMap gracefully removes their entry, ensuring your memory isn't cluttered with unnecessary guests.

How you can use WeakHashMap in your Java programs:

java
import java.util.WeakHashMap;

public class WeakHashMapExample {
    public static void main(String[] args) {
        // Create a WeakHashMap to hold magical guests and their powers
        WeakHashMap<Wizard, String> magicalGuests = new WeakHashMap<>();

        // Create some wizard guests
        Wizard harry = new Wizard("Harry");
        Wizard hermione = new Wizard("Hermione");
        Wizard ron = new Wizard("Ron");

        // Add the wizards to the WeakHashMap
        magicalGuests.put(harry, "Invisibility Cloak");
        magicalGuests.put(hermione, "Time Turner");
        magicalGuests.put(ron, "Deluminator");

        // Let's check the magical guests
        System.out.println("Magical guests at the tea party: " + magicalGuests);

        // Now, let's make some of them disappear
        ron = null;
        System.gc(); // Request garbage collection

        // Check the guests again
        System.out.println("Magical guests after Ron leaves: " + magicalGuests);
    }
}

class Wizard {
    private String name;

    public Wizard(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

In this enchanting example, we create a WeakHashMap to hold our magical guests and their powers. Each wizard is represented by an instance of the Wizard class, and their names serve as the keys in our WeakHashMap. However, when a wizard decides to leave the tea party (i.e., their reference becomes weak), WeakHashMap gracefully removes their entry, keeping our memory tidy and efficient.

Example

java
import java.util.WeakHashMap;

public class WeakHashMapExample {
    public static void main(String[] args) {
        WeakHashMap<Key, String> weakHashMap = new WeakHashMap<>();
        Key key1 = new Key("key1");
        Key key2 = new Key("key2");

        weakHashMap.put(key1, "Value 1");
        weakHashMap.put(key2, "Value 2");

        System.out.println("WeakHashMap before garbage collection: " + weakHashMap);

        // Let's make key1 eligible for garbage collection
        key1 = null;

        // Run garbage collection
        System.gc();

        System.out.println("WeakHashMap after garbage collection: " + weakHashMap);
    }

    static class Key {
        private String name;

        Key(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Key{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
}

In our example, we create a WeakHashMap and populate it with two keys (key1 and key2). After that, we make key1 eligible for garbage collection by setting it to null. Finally, we invoke the garbage collector, and you'll notice that key1 is no longer present in the WeakHashMap after garbage collection runs.

Isn't that simply magical? With WeakHashMap, we can gracefully handle situations where keys are no longer needed, allowing the garbage collector to work its magic and keep our memory footprint in check.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.