Yes, it is possible, but not very simple.
The problem with using java.lang.instrument.Instrumentation is that you ALWAYS have to use the JVM agent. A good introduction to JVM agents is available at http://www.javabeat.net/2012/06/introduction-to-java-agents/ .
However, since your unit tests also run in jvm, you can specify an agent as a JVM argument.
A JVM agent for reporting on the state of memory that you want to make and ready for packaging is available at https://github.com/jbellis/jamm . You can build it with either Maven or Ant. To use it, you create it and then pass the following as a jvm argument when you run the unit test or unit test suite:
-javaagent:<path to>/jamm.jar
As part of unit tests, you can create an instance of MemoryMeter and use it:
MemoryMeter meter = new MemoryMeter(); meter.measure(object); meter.measureDeep(object); meter.countChildren(object);
Integrating stuff
source share