Sobes.tech
Junior — Middle

Under what conditions and in what situations does Java invoke the garbage collector for different types of references?

sobes.tech AI

Answer from AI

In Java, the garbage collector (GC) automatically frees memory when objects become unreachable. Types of references affect when an object is considered reachable:

  • Strong Reference — a normal reference. The object will not be collected as long as there is at least one strong reference.
  • Soft Reference — the object may be collected when memory is low, but it is usually retained.
  • Weak Reference — the object may be collected during the next GC cycle if there are no strong references.
  • Phantom Reference — used to track object removal; the object is already considered unreachable.

The garbage collector is invoked when:

  • Memory runs out or a threshold is reached.
  • The JVM decides to optimize memory usage.

Objects with strong references live longer, soft and weak references can be collected earlier, and phantom references are used for special purposes.

Example of using a weak reference:

WeakReference<MyObject> weakRef = new WeakReference<>(new MyObject());
// If there are no more strong references, the object may be collected by GC