SLF4J是否是线程安全的? [英] Is SLF4J thread-safe?
问题描述
我可能有一个 Dog
类,它在多个线程中共享一个实例。我计划将SLF4J用于所有日志记录:
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?
推荐答案
总之: LoggerFactory.getLogger(Class<?>)
caches Logger
基于类的实例。因此,如果我两次调用 LoggerFactory.getLogger(Dog.class)
,我将在内存中获得对同一对象的2个引用。这意味着如果2个线程实例化 Dog
,它们将获得相同(共享)Dog Logger
实例。
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.
因此SLF4J API 不线程安全。这完全取决于您选择的绑定。看起来常见的绑定(log4j,JUL和logback)是线程安全的,所以即使多个线程可以访问相同的Dog Logger
,log4j / JUL / logback也是如此。记录器绑定是线程安全的,所以你没有问题。
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.
例证:如果你正在制作自己的SLF4J绑定,那么你所有的记录器
impl方法 synchronized
,或以不同方式解决线程安全问题(提供 ThreadLocal
等等。)。
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.).
这篇关于SLF4J是否是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!