- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在为我们的应用程序设计一个自定义日志记录框架。
我正在阅读Patterns For Logging Diagnostic Messages ,正在 http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/NDC.html 中使用
第 3 页上写着:
Because it is a Singleton, it easily preserves the order of the messages.
我认为,例如,给定 Singleton 类 S,如果类 B 试图获取 S 的实例,而类 A 已经获取了实例 S,则 B 无法获取 S 的实例,因为 A 已经获取了该实例S.
这就是根据我的理解保留消息顺序的原因。
我的理解正确吗?
类 B 如何知道类 A 已完成类 S 并且不再需要它,以便 B 可以获取 S?
如果我的理解是正确的,并且 Singleton 类 S 是否有一些方法: test1() 和 test2() ,如下所示。
test1() 和 test2() 是线程安全的吗?
这些方法将在类 S 之外调用,类似于
S.getInstance().test1("消息")
例如,A 类或 B 类。
这意味着当类 A 和类 B 尝试通过调用 test1() 在日志文件中写入一些数据时,这些数据将按照获取 S 实例的顺序写入?
如果不是,为了使单例类 S 中的方法线程安全,我是否还应该在方法 test1() 和 test2() 上使用 synchronized
关键字或 lock
进行这些方法?
public class S { // singleton class S
private static S instance;
private S(){}
public static S getInstance(){
if(instance == null){
instance = new S();
}
return instance;
}
public static void test1(String log) {
// writing some data to a log file
}
public static void test2(String log) {
// writing some data to a log file
}
}
最佳答案
这绝对不是线程安全的。假设我有两个线程 T1 和 T2,并且 S 具有属性 foo。假设T1和T2正在修改foo的值,然后使用foo的值执行一些其他操作。
然后,我可能可以让 T1 访问 S.getInstance,检查 getInstance 是否未设置,同时,T2 可以访问 S.getInstance 并查看该实例是否未设置。然后,T1 可能会设置实例,但由于 T2 也同时检测到实例未设置,因此也会为 S 设置实例。因此,S.instance 的值实际上将是由T2设定。换句话说,T1 和 T2 之间存在竞争条件,看谁可以先设置 S 的实例。
为了使其同步,您绝对应该同步 getInstance 方法,这样只有一个线程可以同时对其进行操作。另外,您可能应该使 S 的实例成为 volatile 的,以确保访问 S 实例的任何线程始终使用“最新”副本。 (因为可能有一个线程在修改该实例时可能正在对该实例执行其他一些读取操作)。
即像这样的东西:
public class S { // singleton class S
private volatile static S instance;
private S(){}
public synchronized static S getInstance(){
if(instance == null){
instance = new S();
}
return instance;
}
public static void test1(String log) {
// writing some data to a log file
}
public static void test2(String log) {
// writing some data to a log file
}
}
另外,这里有一个很好的链接,说明为什么应该使用 volatile:
What is the point of making the singleton instance volatile while using double lock?
关于java - 单例类中的方法是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48714194/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!