Win a copy of Head First Android this week in the Android 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Two threads logging simultaneously with log4j2

 
Marshal
Posts: 3716
523
Android Eclipse IDE TypeScript Redhat MicroProfile Quarkus Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 3716
523
Android Eclipse IDE TypeScript Redhat MicroProfile Quarkus Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 22508
122
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic