Search code examples
javagarbage-collectionjvm

How can we know whether an object is marked as garbage by GC?


Is there any tool to visualize the status of GC on a specific object?


Solution

  • If you can access the object, it is trivially not collectable.

    The JVMTI system (Java Virtual Machine Tool Interface) lets other processes link up to a JVM and get stats from it. It's what debuggers and profilers use; visualvm (ships with most JDKs) can do this, as can many commercial offerings. They give you some GC insights.

    The JDK itself can do so as well, using -XX:+PrintGCDetails - read this article for more.

    From within the same JVM, you can use the classes in java.lang.ref to make references to objects without impeding garbage collection. Trivially:

    class Test {
      private final WeakReference<String> weakRef;
    
      public void test() {
        String y = new String("");
        weakRef = new WeakReference<>(y);
      }
    
      public boolean hasItBeenCollectedYet() {
        // weak refs don't impede collection; `.get()` returns null once
        // the object begins its collection process.
        return weakRef.get() == null;
      }
    }
    

    But, using that system to just gather up general stats? It's not great at it - the other two options are much nicer.