IntelliJ IDEA Tips & Tricks

Profiling Tutorial: Fixing the Parrot Party

We often find ourselves in situations where code is not working properly, and we have no idea where to even begin investigating.

Can’t we just stare at the code until the solution eventually comes to us? Sure, but this method probably won’t work without deep knowledge of the project and a lot of mental effort. A smarter approach would be to use the tools you have at hand. They can point you in the right direction.

In this post, we’ll look at how we can use some of IntelliJ IDEA’s built-in tools to investigate a runtime problem.

Note: This post shows how to use features of both the Community and Ultimate versions of IntelliJ IDEA. To use the profiling tools, make sure you have IntelliJ IDEA Ultimate.

The problem

Let’s start with cloning the following repository: https://github.com/flounder4130/party-parrot

Launch the application using the Parrot run configuration included with the project. The app seems to work well: you can tweak the animation color and speed. However, it’s not long before things start going wrong.

After working for some time, the animation freezes with no indication of what the cause is. There can also be a OutOfMemoryError, whose stack trace doesn’t tell us anything about the origin of the problem.

A frozen animation with still responsive UI

There is no reliable way of telling how exactly the problem will manifest itself. The interesting thing about the animation freeze is that we can still use the rest of the UI.

Important: We run this using Amazon Corretto 11. The result may differ on other JVMs or even on Corretto 11 if it uses a custom configuration.

Debugger

It seems we have a bug. Let’s try using the debugger! Launch the application in debug mode, wait until the animation freezes, then hit Pause.

The debugger shows that all threads are waiting.

Unfortunately, this did not tell us much because all the threads involved in the parrot party are in the waiting state. We don’t even know if the threads are waiting for a lock or have just finished their current work. Clearly, we need to try another approach.

CPU and Memory Live Charts

Since we are getting an OutOfMemoryError, a good starting point for analysis is CPU and Memory Live Charts. They allow us to visualize real-time resources usage for the processes that are running. Let’s open the charts for our parrot app and see if we can spot anything when the animation freezes.

Memory usage chart

Indeed, we see that the memory usage is going up continually before reaching a plateau. This is precisely the moment when the animation hangs, and there seems to be no way out of this.

This gives us a clue. Usually, the memory usage curve is saw-shaped: the chart goes up when new objects are allocated and periodically goes down when the memory is reclaimed by the garbage collector. You can see an example of this in the picture below:

Normal memory usage

If the saw teeth become too frequent, it means that the garbage collector is having a hard time trying to reclaim the memory. A plateau means it can’t free up any.

We can test it by requesting garbage collection from CPU and memory live charts.

GC button in CPU and Memory Live Charts

Memory usage does not go down after our app reaches the plateau. This supports our hypothesis that there are no objects eligible for garbage collection.

A naïve solution would be to just add more memory.

Specifying VM option to add more memory

However, regardless of the available memory, the parrot runs out of memory anyway. Again, we see the same picture. The only visible effect of extra memory was that we delayed the end of the “party”.

The memory usage chart shows that memory is still insufficient

Allocation Profiling

Since we know our application never gets enough memory, we might want to analyze its memory usage.

Let’s run the application with Async Profiler attached. It’s a great choice for CPU profiling. But that’s not all – starting with version 2.0, which is integrated into IntelliJ IDEA, we get the ability to profile memory allocations as well.

Note: If you’re on Windows, use Java Flight Recorder for allocation profiling.

Launching the same run configuration with the profiler attached.

While running, the profiler records the application state when objects are placed on the heap. This data is then aggregated in a human-readable form to give us an idea of what the application was doing when allocating these objects.

After running the profiler for some time, let’s open the report and see what’s there.

Click the balloon to open the profiling report.

There are several views available for the collected data. In this tutorial, we will use the flame graph. It aggregates the collected stacks in a single stack-like structure, adjusting the element width according to the number of collected samples. The widest elements represent the most massively allocated types during the profiling period.

Click the balloon to open the profiling report.

An important thing to note here is that a lot of allocations don’t necessarily indicate a problem. A memory leak happens only if the allocated objects are not garbage-collected. While allocation profiling doesn’t tell us anything about the garbage collection, it can still give us hints for further investigation.

Let’s see where the two most massive elements, byte[] and int[], come from. The top of the stack tells us that these arrays are created during image processing by the code from the java.awt.image package. The bottom of the stack tells us that all this happens in a separate thread managed by an executor service. We aren’t looking for bugs in library code, so let’s look at the user code that’s in between.

Going from top to bottom, the first application method we see is recolor(), which in turn is called by updateParrot(). Judging by the name, this method is exactly what makes our parrot move. Let’s see how this is implemented and why it needs that many arrays.

Click Jump to Source to navigate to the corresponding piece of code

Clicking at the frame and selecting Jump to Source takes us to the source code of the corresponding method:

The implementation of the updateParrot() method

It seems that updateParrot() takes some base image and then recolors it. In order to avoid extra work, the implementation first tries to retrieve the image from some cache. The key for retrieval is a State object, whose constructor takes a base image and a hue.

Analyzing Data Flow

Using the built-in static analyzer, we can trace the range of input values for the State constructor call. Right-click the baseImage constructor argument, then from the menu, select Analyze | Data Flow to Here.

Expand the nodes and pay attention to ImageIO.read(path.toFile()). It shows us that the base images come from a set of files. If we double-click this line and look at the PARROTS_PATH constant that is nearby, we discover the files location:

That’s ten base images that correspond to the possible positions of the parrot. Well, what about the hue constructor argument?

If we inspect the code that modifies the hue variable, we see that it has a starting value of 50. Then it is either set with a slider or updated automatically from the updateHue() method. Either way, it is always within the range of 1 to 100.

So, we have 100 variants of hue and 10 base images, which should guarantee that the cache never grows bigger than 1000 elements. Let’s check if that holds true.

Conditional Breakpoints

Now, this is where the debugger can be useful. We can check the size of the cache with a conditional breakpoint.

Let’s set a breakpoint at the update action and add a condition so that it only suspends the application when the cache size exceeds 1000 elements.

Now run the app in debug mode.

Indeed, we stop at this breakpoint after running the program for some time. So we can be sure that the problem is in the cache.

Inspecting the Code

Cmd + B on cache takes us to its declaration site:

private static final Map<State, BufferedImage> cache = new HashMap<>();

If we check the documentation for HashMap, we’ll find that its implementation relies on the equals() and hashcode() methods, and the type that is used as the key has to correctly override them. Let’s check it. Cmd + B on State takes us to the class definition.

Seems like we have found the culprit: the implementation of equals() and hashcode() isn’t just incorrect. It’s completely missing!

Override Methods

Writing implementations for equals() and hashcode() is a mundane task. Luckily, IntelliJ IDEA can generate them for us. While in the State class, start typing equals, and the IDE will understand what we want.

Just accept the suggestion and click Next until the methods appear at the caret.

Hint: You can also use this as a quick way to override other members or generate accessor methods. For example, typing get will show you the suggestions to generate getter methods.

Checking the Fix

Let’s restart the application and see if things have improved. Again, we can use CPU and Memory Live Charts for that:

That is much better!

Summary

In this post, we looked at how we can start with the general symptoms of a problem and then, using our reasoning and the variety of tools IntelliJ IDEA offers us, narrow the scope of the search step-by-step until we find the exact line of code that’s causing the problem. More importantly, we made sure that the parrot party will go on no matter what!

If you are interested in more detailed instructions on how to use the features from this post, feel free to check out the documentation:

As always, we will be happy to hear your feedback. Please use the comments section to tell us if there are scenarios or features that you would like us to cover in future posts in this series.

For feature requests feel free to reach out to us in YouTrack.

Happy developing!

image description