Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java GC - is there a way to determine which objects collected

I'm trying to monitor the gc activity in my app, using -verbosegc flag. I can see there are full and minor collections, but is there a way to determine (subscrbing to events/vm flags/whatever) which objects actually collected?

Thanks!

like image 610
Seffi Avatar asked Apr 13 '10 11:04

Seffi


People also ask

How does garbage collector know which objects to free Java?

When the garbage collector performs a collection, it releases the memory for objects that are no longer being used by the application. It determines which objects are no longer being used by examining the application's roots.

Which objects are garbage collected in Java?

Java Garbage collector tracks the live object and objects which are no more need are marked for garbage collection. It relieves developers to think of memory allocation/deallocation issues. When an object created in Java program is no longer reachable or used it is eligible for garbage collection.

How do I know which GC is used by JVM?

For modern computer (multiple cpus, big memory), JVM will detect it as server machine, and use Parallel GC by default, unless you specify which gc to use via JVM flags explicitly.

In which package do we have the class which has GC method?

gc() method located in the java. lang package.


1 Answers

For general information about objects in memory I would suggest you look into jvisualvm (it is in the bin folder of your JDK). It has alot of useful information about what the VM is doing as your program runs, including information about the various objects, and memory state.

If you want something more specific you can use WeakReferences and ReferenceQueues. This option might be viable if you are only interested in objects of a few type. You can create a WeakReference to the objects as they are created with a common ReferenceQueue, and then have another thread check the Queue periodically (note that the queue only says the objects are reachable, not that they are actually collected):

static ReferenceQueue<MyObject> MY_QUEUE = new ReferenceQueue<MyObject>();
static class MyReference extends WeakReference<MyObject>{
  public final String name;
  public MyReference(MyObject o, ReferenceQueue<MyObject> q){
    super(o, q);
    name = o.toString();
  }
}

static{
  Thread t = new Thread(){
    public void run(){
      while(true){
        MyReference r = (MyReference)MY_QUEUE.remove();
        System.out.println(r.name+" eligible for collection");
      }
    }
  }
  t.setDaemon(true);
  t.start();
}

public MyObject(){
  //normal init...
  new MyReference(this, MY_QUEUE);
}
like image 133
M. Jessup Avatar answered Sep 30 '22 18:09

M. Jessup