Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4j: is it synchronized for multithreaded calls?

We are running into an interesting issue that we noticed while doing stress testing of our system. We are using log4j (in JBOSS) very heavily for our logging. Here is a naive example of some logging we ave

void someFunction()
{
Log.info("entered some function");
...

Log.info("existed some function");
}

Now the interesting thing we noticed is that if we launch 100 threads against this function; the Log.info() calls is blocking per thread.. meaning thread 2 is waiting for thread1 to finish the "Log.info" call. In case of Thread 100; it ends up waiting quite a long time.. We are using a native file logger.

Is this a known issue?

like image 395
shergill Avatar asked Feb 18 '12 18:02

shergill


People also ask

Is multithreading synchronized?

Synchronization in java is the capability to control the access of multiple threads to any shared resource. In the Multithreading concept, multiple threads try to access the shared resources at a time to produce inconsistent results. The synchronization is necessary for reliable communication between threads.

Is multithreading actually concurrent?

In a multithreaded process on a single processor, the processor can switch execution resources between threads, resulting in concurrent execution. Concurrency indicates that more than one thread is making progress, but the threads are not actually running simultaneously.

Are loggers thread-safe?

All sinks added to the logger are thread-safe by default. They are not multiprocess-safe, but you can enqueue the messages to ensure logs integrity.

Is log4j logger thread-safe?

Yes, log4j is thread-safe. Log4j components are designed to be used in heavily multithreaded systems.


1 Answers

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.

like image 198
Tomasz Nurkiewicz Avatar answered Oct 17 '22 17:10

Tomasz Nurkiewicz