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!
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.
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.
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.
gc() method located in the java. lang package.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With