Log4j: is it synchronized for multithreaded calls? Log4j: is it synchronized for multithreaded calls? multithreading multithreading

Log4j: is it synchronized for multithreaded calls?


Log4J has to be synchronized, otherwise you would see interleaved and garbled log messages in your file. But at least in Logback only appenders are synchronized, not the whole logging message (so computing effective log level, log message, etc. is multi-threaded).

However even if synchronization was removed, I/O would be the bottleneck since it is inherently single-threaded. Thus consider reducing the amount of logging, since it is the file access that is slow, not Log4J.

You may also be interested in AsyncAppender to queue logging messages in a single, different thread.


Yes, log4j uses multithread syncronyzation. And not perfectly, sometimes.

We had experienced some performance degradation caused by contention for log4j locks and even deadlocks with use of complex toString() method.

See https://issues.apache.org/bugzilla/show_bug.cgi?id=24159 and https://issues.apache.org/bugzilla/show_bug.cgi?id=41214#c38, for example.

More details in my another answer:Production settings file for log4j?

I guess this is one of the reasons of logback existence and switch to custom logmanager since JBoss AS 6.


What you might want is asynchronous logging, see this article on how to achieve that:

Asynchronous logging with log4j

Also, consider using the right log levels. The entered... and exi(s)ted... statements should typically be logged at TRACE level, which might be handy when debugging (then set configure log4j to log at TRACE level as well). In a production setting you might want to tell log4j to log only from level INFO or DEBUG, thus avoiding unnecessary log actions.

See also this question on the performance of log4j:

log4j performance