Akash Nisar
Akash Nisar

Reputation: 31

why log4j gc free logging is not suitable for webapp

I am currently migrating our web services and web application to use Log4j 2.6 logging. Based on the information provided on the website, web application supports partial garbage free logging and does not support full garbage free logging because of the possibility of memory leak. Can anyone help me to understand how logging works if we set TreadLocal enabled in first case and ThreadLocal disable in the second case.

Also, I would like know in what scenarios partial garbage free logging is better than full garbage free logging.

Upvotes: 3

Views: 323

Answers (1)

Remko Popma
Remko Popma

Reputation: 36844

In garbage free mode, Log4j2 reuses LogEvent objects. To prevent multiple threads from modifying the same LogEvent at the same time, each thread has its own LogEvent. This is implemented with ThreadLocal.

A key point of ThreadLocals is that whatever is put in them remains there until it is explicitly removed or the thread dies. Even if there are no other references to our LogEvent, it will not be garbage collected because the ThreadLocal still has a reference to it, and threads are GC roots.

Web application containers often load a web application in a custom class loader. This allows stopping and reloading different versions of a web application without restarting the web application container. However, if something still has a reference to a class of the previous version of the web app, that class, and all associated classes, including the custom class loader, cannot be garbage collected.

When could this happen? When the web application container has a thread pool that is shared between web applications, and not flushed when the web app is reloaded. Threads in the pool then still have ThreadLocal references to a LogEvent object and class of the previous version of the web app, so this class cannot be garbage collected, and you have a memory leak.

Conclusion You can use garbage free logging in web apps if both of the following conditions are true:

  1. Thread pools are not shared between web applications
  2. When a web application is reloaded, its thread pool is also shut down and restarted

If the above are both true, I believe you can configure Log4j2 to use garbage free logging without risking memory leaks. Of course you'll need to do due diligence and test.

Upvotes: 3

Related Questions