Estimating the memory usage of a java object

JDK 1.5 introduces the java.lang.instrument package which provides services that allow java programming agents to instrument programs running on the JVM. In simple words an agent is an interceptor in front of your main method, executed in the same JVM and loaded by the same system classloader, and governed by the same security policy and context.

We can create an instrumentation agent in Java by writing a class containing a premain(String, Instrumentation) method. This method is called by the JVM on startup and an instance of Instrumentation is passed in.

import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}

Since an agent has to be packaged in a jar file, compile the above class and package it in a jar file. Add a MANIFEST.MF file in the jar file under META-INF folder. The MANIFEST.MF file should contain the below line
Premain-Class: ObjectSizeFetcher

Use getObjectSize method

public class C {
   private int x;
   private int y;

   public static void main(String [] args) {
     System.out.println(ObjectSizeFetcher.getObjectSize(new C()));
   }
}

Invoke the above class C using the below command
java -javaagent:<path to objectsizefetcheragent.jar> C

Note that the instrumentation interface gives you a flat size of the object and does not recursively estimate the size of the objects that it references. To calculate the deep size of an object have a look at this article from java specialist.

Advertisements

Posted on May 19, 2011, in java and tagged , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: