• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Ganesh Patekar

Two threads logging simultaneously with log4j2

 
Saloon Keeper
Posts: 2722
354
Android Eclipse IDE Angular Framework MySQL Database TypeScript Redhat Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an application where I want to log messages to a common logger from two different threads.

In the example below, I am expecting that the the messages from both threads will be printed to System Out, but if I run the code as-is, I only seethe message from the second thread, and if a add a sleep/yield between the two threads, I only see the message from the first thread.

I can work-around the issue by place a queue between the threads and the logger, so that only a single thread to logging, but I would prefer not to have to do this.

Any suggestions on how I can over-come this problem?


Test code:
log4j2.xml:
Work-around:
OS: Windows 10 64 bit version 1709
JRE: 1.8.0_171-b11
log4j2: 2.10.0
 
Ron McLeod
Saloon Keeper
Posts: 2722
354
Android Eclipse IDE Angular Framework MySQL Database TypeScript Redhat Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It seems like LogManager.getLogger() may not be thread friendly.  If I create the Logger reference outside of the threads and share it with the threads, it does work as expected.
 
Sheriff
Posts: 21804
104
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not use a private static final Logger field? The logger name is fixed, so why not make the Logger fixed as well?
 
The fastest and most reliable components of any system are those that are not there. Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!