Sobes.tech
Middle

What types of links exist in Java and what are their differences?

sobes.tech AI

Answer from AI

In Java, there are strong, soft, weak, and phantom references.

Strong Reference:

  • Assigned in the usual way.
  • The object referenced by a strong reference will not be garbage collected as long as there is at least one strong reference to it.
Object obj = new Object(); // strong reference

Soft Reference:

  • The object referenced by a soft reference may be garbage collected only if the system runs out of memory.
  • Often used for implementing caches.
SoftReference<Object> softRef = new SoftReference<>(new Object());
Object obj = softRef.get(); // may return null if the object was collected

Weak Reference:

  • The object referenced by a weak reference can be garbage collected at any moment as soon as there are no strong references to it.
  • Used to prevent memory leaks, for example, when storing listeners or contexts.
WeakReference<Object> weakRef = new WeakReference<>(new Object());
Object obj = weakRef.get(); // may return null at any moment

Phantom Reference:

  • The object referenced by a phantom reference will not be collected until all phantom references to it are cleared.
  • Cannot access the object via get().
  • Used in conjunction with ReferenceQueue to perform actions after the object becomes eligible for collection but before the memory is actually freed. Used for more complex resource management than with finalize().
ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
PhantomReference<Object> phantomRef = new PhantomReference<>(new Object(), referenceQueue);
// phantomRef.get() always returns null

The main differences are summarized in the table:

Reference Type Garbage Collection Criterion Ability to access object via get() Usage
Strong Only if no strong references Yes Regular use
Soft If memory is low Yes (may be null) Caching
Weak If no strong references exist Yes (may be null) Preventing memory leaks (listeners, contexts)
Phantom After all phantom references are cleared (in conjunction with ReferenceQueue) No (always null) Advanced resource management, replacing finalize()
What types of links exist in Java and what are their… - sobes.tech