Is SLF4J thread-safe?

戏子无情 提交于 2019-12-03 23:19:36

问题


I might have a Dog class that has a single instance shared across multiple threads. I plan on using SLF4J for all logging:

public class Dog {
    private Logger logger = LoggerFactory.getLogger(Dog.class);

    // ...etc.
}

Is my logger instance thread safe? Why/why not?


回答1:


Certainly, everyone assumes that a Logger is going to be thread-safe. But you would need to look at the code / javadocs of the implementation classes behind the facade to be absolutely sure.

For specific implementations:

  • Log4j 1.2 is thread-safe
  • java.util.logging.Logger is thread-safe (search for "multi-thread safe")
  • Logback is thread-safe

(Obviously, these are statements that the respective code is designed to thread-safe. There can always be bugs. For example, there are currently a couple of open thread-safety bugs in the Log4j 2 tracker, though it doesn't seem like those bugs would directly affect your example code.)




回答2:


In conclusion: LoggerFactory.getLogger(Class<?>) "caches" Logger instances based on class. So if I call LoggerFactory.getLogger(Dog.class) twice, I'll get 2 references to the same object in memory. This means that if 2+ threads instantiate a Dog, they'll both get the same (shared) Dog Logger instance.

So the SLF4J API is not thread-safe. It's all up to the binding you choose. It looks like the common bindings (log4j, JUL and logback) are thread-safe, so even if multiple threads get access to the same Dog Logger, the log4j/JUL/logback logger binding is thread-safe, so you have no issues.

Case in point: if you are making your own SLF4J binding, make all your Logger impl methods synchronized, or address thread-safety in a different way (providing ThreadLocal, etc.).



来源:https://stackoverflow.com/questions/18543642/is-slf4j-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!