Video in progress
What is the difference between strong, soft, weak and phantom references as far as the GC is concerned?
When the GC collects it / Where it is used — Strong (Foo f = ...): never, as long as the reference exists / ordinary code; SoftReference: when the heap is tight, before an OOM / memory-sensitive caches; WeakReference: at the next GC, if there is no other strong reference / metadata, listener lists; PhantomReference…
📖 Answer
| Type | When the GC collects it | Where it is used |
|---|---|---|
Strong (Foo f = ...) |
never, as long as the reference exists | ordinary code |
SoftReference |
when the heap is tight, before an OOM | memory-sensitive caches |
WeakReference |
at the next GC, if there is no other strong reference | metadata, listener lists |
PhantomReference |
you get notified after the object has already been collected | cleaning up native resources, inside Cleaner |
var ref = new WeakReference<>(new byte[1024]);
System.gc();
System.out.println(ref.get()); // most likely null
Keep in mind that get() can return null at any time: first assign the result to a local variable, then check it for null.
A soft-reference cache looks convenient, but on prod it becomes unpredictable: when the heap gets close to full, the GC clears everything at once, the cache is suddenly empty and the load on the database jumps. That is why I prefer Caffeine, with a size or time limit, for caches.
Sign up to mark studied questions and save your progress.