JavaAdvanced#memory#gc

What is the difference between strong, weak, soft, and phantom references?

Strong references prevent GC entirely. Soft references are cleared only when memory is low (good for caches). Weak references are cleared at the next GC cycle regardless of memory pressure (good for canonicalizing maps). Phantom references are used for cleanup actions after an object is finalized.

Example
WeakReference<Object> weakRef = new WeakReference<>(new Object());
// object can be GC'd even though weakRef exists, once no strong refs remain

Related Questions

1
JavaAdvanced#gc#jvm

What is the difference between G1, CMS, and ZGC garbage collectors?

Open
2
JavaIntermediate#gc#memory

What is the purpose of the finalize() method and why is it discouraged?

Open
3
JavaIntermediate#serialization

What is serialization in Java?

Open