Java.Collections.What is weak reference ?

In Java, a weak reference is a type of reference that does not prevent an object from being garbage collected.

✅ In plain terms:

If an object is only weakly referenced (i.e., no strong references point to it), then the GC is free to collect it at any time — even if it’s still “reachable” through that weak reference.

import java.lang.ref.WeakReference;

public class WeakRefExample {
    public static void main(String[] args) {
        String strong = new String("Hello");
        WeakReference<String> weak = new WeakReference<>(strong);

        System.out.println("Before GC: " + weak.get()); // "Hello"

        strong = null;  // Remove strong reference
        System.gc();    // Suggest garbage collection

        // Wait a bit to give GC a chance
        try { Thread.sleep(500); } catch (InterruptedException e) {}

        System.out.println("After GC: " + weak.get()); // null (if GC ran)
    }
}

📦 Reference Types in Java

Reference TypeGC BehaviorExample Use Case
StrongNever collected unless unreachableNormal variables
WeakCollected as soon as no strong refsWeakHashMap, caches
SoftCollected only when memory is lowMemory-sensitive caches
PhantomUsed for final cleanup (rare)Advanced GC tracking

✅ Use Cases for Weak References

  1. WeakHashMap:
    • Keys are weak references.
    • When a key is no longer strongly referenced, it’s automatically removed from the map.
  2. Caches:
    • Store data that can be discarded if not in use anymore.
  3. Avoiding memory leaks:
    • When you want to refer to something without preventing it from being garbage collected.

⚠️ Gotchas

  • You can’t rely on when the GC will clear weak references.
  • weakRef.get() can return null at any time, so always check before using.

🧠 TL;DR:

A weak reference lets you point to an object without preventing it from being garbage collected.
Useful for caches, observers, and memory-sensitive structures.

This entry was posted in Без рубрики. Bookmark the permalink.