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

Viewed 134

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

2 Answers

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.

The short answer is that there isn't a good way.

And there isn't any way to do it within a program that doesn't (in various ways) alter the behavior of the object that you trying to examine.

The "not good" ways are:

  • By using Reference types. The problem is that this alters the object's lifetime, and only tells you the object's status at the last point in time that the GC ran.

  • By taking a heap dump and examining it with a heap dump analyzer. The problem is that taking a heap dump is an expensive "stop the world" event, it uses a lot of disk space and it needs a lot of RAM to load and analyze the dump.

Finally, you probably won't learn much by doing this unless you are searching for a suspected memory leak.

Related