• 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:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

Can logger instance be static in multithreaded app?

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In a multithreaded application, can a logger (log4j) instance be static?


I have a static method that uses logging messages, something like the code below

Public Foo{

private static Logger logger = Logger.getLogger(Foo.class.getName());

public static boolean doSomething(Boo boo){
....do something with boo.....

logger.debug("something happened");

return true/false;
}

If I want the method to be static, I have to declare my logger instance to be static. Since static variables are 1 per class and will be shared among all the instances of the class Foo, can we declare the logger instance as static?. If all the instances of class Foo try to log the messages to the one logger instance, it may cause problems, like dirty writes, am I correct? I don't want to make the method or logger instance synchronized, that's gonna hit the performance big time. In such case how to deal with the static methods that need logging in multithreaded app.

Appreciate much your replies.

Thanks,
Jack.

 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch.

What you're really asking is if a Log4J Logger is thread-safe. The Log4J FAQ answers this question:

Log4J FAQ wrote:
7. Is log4j thread-safe?

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

 
Ranch Hand
Posts: 608
Firefox Browser Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes log4J synchronizes writes (unless you use an Async appender). Watch out could be a performance problem in really big systems!
 
Story like this gets better after being told a few times. Or maybe it's just a tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic