Middle
What is WeakHashMap used for in Java?
sobes.tech AI
Answer from AI
WeakHashMap is used to create a map where keys are held with weak references. This means that if there are no strong references to a key object other than the weak reference in the WeakHashMap, the garbage collector can remove the key and its associated entry.
Main use cases:
- Caching: When you want to store temporary data related to objects without preventing their garbage collection. For example, caching metadata for each class instance.
- Listener registry: When you want to register listeners for objects but do not want the existence of the listener to prevent garbage collection of the listened object.
- Temporary related data storage: When data is tightly coupled with the lifecycle of another object.
Difference from HashMap:
| Feature | HashMap |
WeakHashMap |
|---|---|---|
| Key retention | Strong references. Keys are retained as long as the map exists or entries are explicitly removed. | Weak references. Keys can be garbage collected if there are no strong references. |
| Behavior | Predictable with respect to key removal | Keys may disappear unpredictably due to garbage collection |
| Usage | General purpose where keys should be retained | Scenarios to avoid memory leaks related to keys |
Example:
// Example of creating WeakHashMap
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;
public class WeakHashMapExample {
public static void main(String[] args) {
WeakHashMap<Object, String> map = new WeakHashMap<>();
Object key = new Object(); // Creating a key object
map.put(key, "value"); // Adding an entry to WeakHashMap
System.out.println("Map contains key: " + map.containsKey(key)); // true
key = null; // Removing strong reference to key object
// Calling System.gc() may speed up garbage collection, but not guaranteed.
// Garbage collection can happen at any moment.
System.gc();
// It may take some time for the garbage collector to delete the entry
// Check if the key still exists after GC
try {
Thread.sleep(100); // Giving some time for GC
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Map contains key after GC: " + map.containsKey(null)); // false (key removed)
}
}