【发布时间】:2014-05-11 02:17:04
【问题描述】:
我正在做一个如下的单例课程。
public class SingletonTest {
private static SingletonTest instance;
private Integer result;
private SingletonTest() {
}
public synchronized static SingletonTest getInstance(){
if(instance == null){
instance = new SingletonTest();
}
return instance;
}
public Integer calculateResult(int value1, int value2) {
result = value1 + value2;
return result;
}
}
但是当我从多个线程(使用 JMeter)调用非静态成员时会出现问题。
举例:
线程 1: SingletonTest.getInstance().calculateResult(1,2) -> 返回 3
线程 2: SingletonTest.getInstance().calculateResult(3,2) -> 返回 3
我认为这是因为 2 个线程同时访问方法并覆盖了名为 result 的 de 属性。
【问题讨论】:
-
嗯,是的 - 你有一个竞争条件。这与它是单例无关,与不安全地改变共享状态有关。您需要同步,或使用
AtomicInteger之类的东西。这里真正的问题是什么? -
是的,这就是“单例”的工作方式。你有一个共享状态的实例。
-
这很有可能 - 您必须应用锁定机制来防止竞争条件。
-
甚至不需要实例变量。
calculateResult方法可以返回一个局部变量。那么就不需要同步了。 -
@fge - 初始化是线程安全的,因为 getInstance 是同步的。
标签: java multithreading methods static singleton