Topics include: programming, Apple, Unix, gadgets, large-scale web sites and other nerdy stuff.

Determine the size of Java objects at runtime.

2007-02-16 16:05:12

This is a great summary of how to do this with the new Instrument package in Java 5+.

The article boils it down very well, but the ultra nutshell version is that you define a class that gets loaded as a "pre-main" agent. First, create a simple implementation of java.lang.instrument.Instrument, creating a manifest file, putting the class file into a jar (with the manifest). Then, start your java application (like tomcat or whatever) with -javaagent:jarfile. Finally, in your code, call your SizeAgent class like this:

   try {
      int size = SizeAgent.sizeOf("some java object, like maybe this string");
   } catch (IllegalStateException e) {
      // size agent is not loaded by -javaagent switch