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
