Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

The Solution — Too Much Fine Logging Causing Heap Dump

DZone's Guide to

The Solution — Too Much Fine Logging Causing Heap Dump

Too much fine logging can still cause heap dump in your Java server. Learn how to prevent this problem.

· Performance Zone ·
Free Resource

Sensu is an open source monitoring event pipeline. Try it today.

Many times, we face issues of heap dump in our Java server. Heap increases because your system is generating many objects, and if their lifecycle is long and the system keeps on generating these objects, they will consume all the RAM and heap dump may occur. This may occur due to memory leaks, bad coding, etc.

But these are not the only reasons for heap dump. Once, I faced an issue with our customer where heap dump was occurring regularly, and after debugging, I found that the root cause of the issue was fine logging. You may be surprised how logging can cause heap dump. 

Too much logging can cause heap dump even if they are fine level logs, not info logs. A surprising fact is that fine logging was not enabled.

Why it happened is as follows:

Generally, we log fine logging like in this example:

logger.fine("fine logs ") .

Now, what happens behind the scenes (in the JVM) is that even if fine logs are disabled except for the string "fine logs," objects will be created as it is passed as an argument if the check for fine logging is inside the fine method.

If there are too many fine logs in the system and there are many threads available doing these operations with lots of fine logs, many char[] objects are created and fill the heap/RAM.

The Solution

There are two ways we should do fine logging.

1. Check the "if" condtion before every fine log, as follows:

if (logger.isFineLoggable()) {

logger.fine("your log ");

}

But, this does not look cool (lots of "if" in the code...)

2. With Java 8, Java gives a new API for logger, which does not take string as an argument; it takes function, which returns string as an argument and evaluates it when this function is called inside the fine method. This way, an object is not created until the function is called.

Here is an example:


logger.fine(() -> "fine logs"); .

With functional programming, the code looks nice and the problem was resolved.

Sensu: workflow automation for monitoring. Learn more—download the whitepaper.

Topics:
java ,heap dump ,logging ,performance ,tutorial ,functional programing ,lamdba

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}