Question

Whenever a new object is created by my JVM I want to print something in the log. I was trying to detect that using Runtime.getRuntime().freeMemory() but unfortunately it does NOT take into account any short-lived object until it is promoted to the heap (check here for more details).

So does anyone know how to detect/track whenever an object is instantiated/created by my JVM? To make it easier, how do we complete the code below:

Feel free to use MemoryPoolMXBean and JMX:

public class MemoryUtils {

    private static Set<String> set = new HashSet<String>();

    public static void main(String[] args) {

        // START

        // now create a bunch of objects and save them in the set
        for (int i = 0; i < 100; i++) {
            set.add(new String("foo" + i));
        }

        // FINISH

        // FIXME: Do something here to detect that a bunch of objects were created!

    }
}

Edit: Trying solution proposed by Vladimir below:

It works, but with a weird side-effect:

long t = totalThreadMemoryAllocated();

// did nothing

t = totalThreadMemoryAllocated() - t;

System.out.println(t); // ==> 48 !!!???

public static long totalThreadMemoryAllocated() {
    com.sun.management.ThreadMXBean tBean = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
    return tBean.getThreadAllocatedBytes(Thread.currentThread().getId());
}

But it DOES account for any object creation so I guess I could use this if I subtract the magic number 48 from it.

Was it helpful?

Solution

you can use a Java agent to do this, open source implementation can be found via the author's blog - http://jeremymanson.blogspot.co.uk/2012/02/update-to-allocation-instrumenter.html

OTHER TIPS

Sun JVM (1.6.0u26 and higher) has ThreadMXBean#getThreadAllocatedBytes method that reports total number of bytes allocated by the thread. That will not distinguish between live/dead memory, however that would allow you to detect memory allocations and measure total amount of those allocations.

To use this approach you just lookup regular ThreadMXBean, and either cast it to com.sun.management.ThreadMXBean or use reflection to invoke the method.

I wrote an open source tool to track object allocation and object lifetimes: http://mchr3k.github.com/org.inmemprofiler/

My tool won't let you log all object allocations to your own log but will perform its own analysis on the assumption that you want to actively track down things like object leaks or excessive object allocation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top