Thursday, December 18, 2008

Sizeof for Java

Version 0.1
Download jar.
Download source.
Online Javadoc.

As promised in my last post, here is a small library that calculates the shallow and deep size of any Java object.

It contains one public class: com.codeinstructions.sizeof.SizeOf, which implements five public methods:

static long deepSize(java.lang.Object object) - Calculates the deep size of an object.
static long deepSize(java.lang.Object object, long maxSize) - Calculates the deep size of an object, but limiting to a certain size, to avoid going deep on a very large tree of objects.
static long depthLimitedDeepSize(java.lang.Object object, int depth) - Returns the deep size of an object, but prunes the search at a certain depth.
static boolean isLargerThan(java.lang.Object object, long size) - Checks if the deep size of an object is larger than a certain limit.
static int shallowSize(java.lang.Object object) - Returns the shallow size of an object.

The full class javadoc can be found here.

How it works

This code uses reflection to get the details about the class so that it can calculate the size of its instances. It also uses reflection to navigate through the object graph in order to calculate the deep size.

It is still experimental, and has currently been tested only in a 32 bit Java 6 Update 11 JDK.

This library is release under a BSD-like public license, which means you can do whatever you want with it as long as you give credit :).

5 comentários:

Jorge Ferreira said...

Nice work Domingos.

Cédrik said...

Great, one more implementation of sizeof() in Java! :-)

Others include (in no particular order):
NetBean's Insane lib
JavaSpecialist's take 1
JavaSpecialist's take 2
a blog entry
SizeOf project (GPL)
Vladimir Roubtsov's article

There may be others I am not aware of... ;-)

For the record, I am using a slightly modified version of Vladimir Roubtsov in MessAdmin to measure the size of an HttpSession.

That said, your implementation is one of first to take into account memory alignment and 32/64 bit architecture. I may very well switch to your implementation, as we have compatible licenses. In the meantime, you may be interested to have a look at MessAdmin's source code to learn about some edge cases (read bugs) that can trigger bad things when reflecting on some objects. Contact me by email for more details.

Stanimir Simeonoff said...

java.lang.instrument.Instrumentation.getObjectSize(Object objectToSize)

Domingos Neto said...

Cédrik, thanks for the info!

I was aware of the existence of some of those implementations, but not all.

But I was never intending to do something really useful: I just wanted to put the theory in the previous post in practice :)

Domingos Neto said...

Stanimir: that method looks like something I could use. Thanks!

Do you know how I can use that method from inside a Java process without having to write an instrumentation agent? It would make life much easier!