Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!