Monday, 6 July 2015

Measuring Allocations Programmatically

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();
...
//critical code
...
assertEquals(0, measure.markAllocations());

Full code for AllocationsMeasure below:


1 comment:

  1. Thanks for sharing here valuable information about Java.I am cheerful to see this information. I essentially welcome you for that kind of effort. I just welcome you and stay behind posting a few. I am so overcome. I think you have a strange get used to in exacting while dealings with such subjects. Training contains various activities like article, task, look at paper create and an general part of the understudies can't complete their task suitably inside the time. Writing an essay is an imperative part of a life and even a slight measure of danger can bring about a major red imprint on your scholastic result. In this way, in the event that you are not certain of yourself that you will effectively pull off these essay composing coursework, then insight is in selecting custom paper composing administrations. Notwithstanding subject and due date, the specialists at best essay writing service are here to guide you through your issues with composing exploration and coursework.

    ReplyDelete