Thursday, December 08, 2011

Querying the memory usage of a Java object

Creating the instrumentation agent class - would work with Jdk 5 and above



The JVM will pass to our method an implementation of the Instrumentation interface, defined in java.lang.instrument. In turn, this interface defines the method getObjectSize(). So for example, if we want to measure the memory usage of an instance of SomeClass, our agent code would look as follows:
import java.lang.instrument.*;
import com.somepackage.SomeClass;

public class MyAgent {
  public static void premain(String args, Instrumentation inst) {
    SomeClass obj = new SomeClass();
    long size = inst.getObjectSize(obj);
    System.out.println("Bytes used by object: " + size);
  }
}
Package the agent into a jar -

create manifest.txt with
Premain-Class: mypackage.MyAgent

execute this to create a jar -

jar -cmf manifest.txt agent.jar mypackage/MyAgent.class

Run the application with the agent -

java -javaagent:agent.jar -cp . com.mypackage.Main

Accessing the Instrumentation object from within our application -

public class MyAgent {
  private static volatile Instrumentation globalInstr;
  public static void premain(String args, Instrumentation inst) {
    globalInstr = inst;
  }
  public static long getObjectSize(Object obj) {
    if (globalInstr == null)
      throw new IllegalStateException("Agent not initted");
    return globalInstr.getObjectSize(obj);
  }
}

Now, provided the agent is included in the JVM command line parameters as above, then from anywhere in our application we can call MyAgent.getObjectSize() to query the memory size of an object created by our Java application

Note that the getObjectSize() method does not include the memory used by other objects referenced by the object passed in.


Next -- Memory footprint of java datatypes




Also Read
Java development 2.0: Ultra-lightweight Java web services with Gretty
An actor framework for Java concurrency
Java Garbage Collection explained
Java collection performance - Chart view
The Clean Coder

1 comment:

javin paul said...

Thanks for sharing this nice tip man. earlier we have only limited to Runtime.freeMemory() etc.

Javin
2 ways to solve OutOfMemoryError in Java