WeakReference holds a referent without keeping it strongly reachable solely through that reference.
Java weak references: reachability is not a cache eviction schedule
Java 8+. This is a complete program using JDK classes.
Keep lifetime separate from lookup
A metadata index can need to observe an object without deciding how long it lives. A weak reference supplies that relationship. It does not promise that an object survives until the next access, and it does not supply a memory budget or a predictable eviction time.
Read get() once into a local variable, check that result, then use the local value. Repeating get() after a successful check creates a second observation rather than holding the first result. A local strong reference keeps the selected object available during that operation.
The example clears its reference explicitly. That makes the result deterministic and tests the absent branch; it is not evidence that a garbage collector runs on demand. System.gc is a request and must not be part of the business condition that makes a cache correct.
Avoid a strong route back
A weak-key map can still retain a key if its strongly held value points back to that key. Draw the actual object references before assuming a weak-key structure resolves retention. ReferenceQueue is useful when cleanup needs notification, but the consumer still needs its own removal policy and resource ownership.
Working program
import java.lang.ref.WeakReference;
public class OptionalMetadataReference {
public static void main(String[] args) {
String record = new String("parcel-42");
WeakReference<String> index = new WeakReference<>(record);
String selected = index.get();
System.out.println(selected != null ? selected : "absent");
index.clear();
System.out.println(index.get() == null);
System.out.println(record);
}
}Output
parcel-42
true
parcel-42Costs and boundaries
Creating or checking one weak reference is constant-sized application work. Collector processing and reference-queue cleanup depend on the runtime and reachable object graph, so this example does not assign a fixed eviction latency. Required cached data needs a deterministic reload path and explicit capacity limits.
Common Mistakes
- Never require a collection to occur before the application can proceed.
- Weak references do not close files or connections for you.
- A strong value-to-key reference can defeat the intended weak-key lifetime.
