In this tutorial we will demonstrate how to use Aprof. Note, that this guide is actual for version 21.
First of all, extract aprof.jar from downloaded zip file with Aprof binaries. This JAR is the file you will be using.
Note, that you should not rename the aprof.jar file, otherwise it will not work.
Aprof comes with integrated help explaining all supported options and their default values. Execute the following line from the console to read it:
You will see that in order to profile your Java application with Aprof you should start JVM with -javaagent:aprof.jar option. For example, to profile well-known SwingSet2 demo you need to start it this way:
That's it! While you are using the demo, Aprof collects its memory allocation statistics and flushes it to aprof.txt file every minute.
In order to understand aprof.txt file you should be aware of the following specifics of Aprof.
Imagine we are interested in allocations of char. Aprof will collect all locations where these allocations take place. Naturally, some of them occur in constructor of String object. However, it is not enough to know that, for instance, 3 char with total size of 120 bytes were allocated at location java.lang.String.<init>. We are also interested in locations from which we called constructor of class String. In order to collect such additional information without taking stack-traces the following method is used.
In Aprof configuration some constructors/methods are marked as tracked. What exactly does that mean? When we mark the method as tracked, we tell Aprof that we are interested in occurrences of the method on stack-trace taken at the moment of memory allocation. The trick we use is the fact that knowledge of the outermost tracked method and location from which it was called is enough to pinpoint the problem. Hence, for each memory allocation the following data is collected by Aprof:
As you can see, AProf also profiles itself.
Aforementioned SwingSet2 demo is a complex application, hence its profiling results are not suitable for this tutorial. We will be using a series of specifically designed samples. Some of them make no sense, some are written in non-optimal way, some might even contain bugs. Most likely you will never see them in real applications. However, they help us demonstrate key features of Aprof.
Let's take a look at the following program.
It calculates nth Fibonacci number and prints it to stdout. However, the method returns Integer instead of int which leads to a lot of garbage generated by the program. In large applications it is usually hard to find all such ineffective pieces of code.
Let's run this program under Aprof.
And look at generated file aprof.txt.
We see that 52% of all memory allocations were made for Integer objects. And almost all of them were done in method fib of class FibonacciNumbers.