Java SLF4J 线程安全吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18543642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:54:38  来源:igfitidea点击:

Is SLF4J thread-safe?

javaloggingthread-safetyslf4jthread-local

提问by

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

我可能有一个Dog类,它具有跨多个线程共享的单个实例。我计划使用 SLF4J 进行所有日志记录:

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

    // ...etc.
}

Is my loggerinstance thread safe? Why/why not?

我的logger实例线程安全吗?为什么/为什么不?

采纳答案by Stephen C

In conclusion: LoggerFactory.getLogger(Class<?>)"caches" Loggerinstances 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 Loggerinstance.

总之:基于类LoggerFactory.getLogger(Class<?>)“缓存”Logger实例。所以如果我调用LoggerFactory.getLogger(Dog.class)两次,我会得到 2 个对内存中同一个对象的引用。这意味着如果 2+ 个线程实例化 a Dog,它们都将获得相同的(共享) DogLogger实例。

So the SLF4J API is notthread-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.

所以 SLF4J API不是线程安全的。这完全取决于您选择的绑定。看起来常见的绑定(log4j、JUL 和 logback)是线程安全的,所以即使多个线程访问同一个 Dog Logger,log4j/JUL/logback 记录器绑定也是线程安全的,所以你没有问题。

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

举个例子:如果您要制作自己的 SLF4J 绑定,请制作所有Loggerimpl 方法synchronized,或者以不同的方式(提供ThreadLocal等)解决线程安全问题。

回答by Stephen C

Certainly, everyone assumesthat a Loggeris going to be thread-safe. But you would need to look at the code / javadocs of the implementation classes behind the facade to be absolutelysure.

当然,每个人都假设aLogger将是线程安全的。但是您需要查看外观背后的实现类的代码/javadoc 才能绝对确定。

For specific implementations:

具体实现:

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

(显然,这些是相应代码被设计为线程安全的声明。总是有错误。例如,当前Log4j 2 跟踪器中有几个开放的线程安全错误,尽管它看起来不像这些错误会直接影响您的示例代码。)