I picked up this tip from the The Java Specialists' Newsletter written by Heinz Kabutz. (For all Java developers wanting to learn what goes on under the covers of the JDK this newsletter is an absolute must!)
Especially for developers writing low latency code but even for normal Java code, allocations is the thing you really want to avoid. See my previous posts 'The First Rule of Optimisation' and 'Revisiting the First Rule of Performance Optimisation: Effects of Escape Analysis' for more details.
Previous to this tip I had always used a profiler to work out my allocations or I suppose you could have used the a call to Runtime to see how much heap memory had been allocated by the JVM.
Using MBeans we are able to query an individual thread for it's allocations. This gives us a very precise way of measuring whether a specific thread has allocated and if so how much has it allocated. In situations where you are coding for zero allocation you can include a call to this code in your tests asserting that there has been no allocation.
Below is a simple class you can use based on the tip from the newsletter.
You'll notice that the constructor does a calibration which adjusts for the amount of allocation created by the bean itself.
There is also some defensive code to ensure that the class is only called from a single thread.
You can call the method markAllocations to find the amount of bytes that have been allocated since the the last mark. printAllocations is a handy method to print the allocations since the last mark to standard out. Allocations are rebased after the class is constructed, a call to reset or a call to markAllocations or printAllocations.
In a test you might have code like this:
Allocations measure = new AllocationsMeasure();
Full code for AllocationsMeasure below: