liveBook · Manning

Weak reference

As explained in 100 Java Mistakes and How to Avoid Them

WeakReference is a Java reference type whose referent may be reclaimed when it is not strongly reachable.

A weak reference points to an object without keeping it strongly reachable. When no strong reference remains, garbage collection can clear the referent, so WeakReference.get() may return null. section 9.10

The main failure is accidental invalidation: code creates a WeakReference, stops using the original object, and later dereferences ref.get() as though the object were guaranteed to exist. That race can produce a NullPointerException. section 9.10

Use weak references deliberately:

  • Use them for discardable objects such as recomputable or reloadable cache entries, not for state that must remain available. section 9.10
  • Use WeakHashMap when map keys should disappear automatically after other code stops referencing them. section 9.10
  • Check the result of get() before use, and preserve a strong reference when an operation requires the referent to remain alive. section 9.10
  • Do not expect different WeakReference instances to compare equal merely because they refer to the same object. section 7.2
Object obj = new Object();
WeakReference<Object> ref = new WeakReference<>(obj);
 #1
System.out.println(ref.get().hashCode());

Inspect the minimal failure pattern in which the original strong reference is no longer used before ref.get() is called. section 9.10

Object obj = new Object();
WeakReference<Object> ref = new WeakReference<>(obj);
System.out.println(ref.get().hashCode());     #1
Reference.reachabilityFence(obj);

Compare the unsafe dereference with reachabilityFence, which preserves the intended reachability through the operation. section 9.10

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains reachability categories, garbage-collection timing, failure behavior, WeakHashMap, and reachabilityFence, but not collector internals.
Examples
Uses minimal Java dereference snippets, WeakHashMap mappings, and a reachabilityFence comparison.
What you can do after
Apply it via WeakHashMap or guarded WeakReference access while avoiding assumptions that the referent remains available.
How it connects
Connects weak references with strong references, soft references, garbage collection, WeakHashMap, and reachabilityFence.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.