Skip to content

Java Object Lifecycle and Strong, Soft, Weak, Phantom Reference

Java has a built-in GC to find the unreachable objects and recycle them. This is a significate future versus C/C++ language that requires developper to manually release the memory, it allow the devlopper to focus on the business and write less error prone code.

The following diagram shows the Java object readchability status.


  • "Strong" Reference

    When one or more threads can access that variable directly without any other reference, its status is "strong" reachable. For example, the variable a is a strong reference in the following code.

    var a = "test";
    When an object is strong reachable, then GC will not recycle it.

  • Soft Reference

    If an object can be accessed through SoftReference, then it's soft reachable.

    The GC will not recycle a soft reachable object, until there is no enough memory. The GC will recycle the soft reachable object before throw OutOfMemoryError.

  • Weak Reference

    Unlike soft reachable objects, the GC will recycle the weak reachable objects. It's just a chance that if that weak reachable object does exist, then reuse it, otherwise, recreate it.

  • Phantom Reference

    Phantom refercen object can't be accessed, it's a post-mortem mechanism, that allow us to do some work before an object is destoried.

  • Unreachable

    The object can be sweeped.