Win a copy of Succeeding with AI this week in the Artificial Intelligence and Machine Learning forum!
  • 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
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Junilu Lacar
Sheriffs:
  • Tim Cooke
  • Jeanne Boyarsky
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • fred rosenberger
  • Frits Walraven

Two threads logging simultaneously with log4j2

 
Marshal
Posts: 3079
459
Android Eclipse IDE TypeScript Redhat MicroProfile Quarkus 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
Marshal
Posts: 3079
459
Android Eclipse IDE TypeScript Redhat MicroProfile Quarkus 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: 21922
106
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?
 
    Bookmark Topic Watch Topic
  • New Topic