简体   繁体   English

Singleton类中的非静态成员

[英]Non static members in Singleton class

I´m doing a singleton class as follows. 我正在按如下方式学习单例课程。

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;
    }
}

But a problem occurs when I call non-static members from multiple threads (with JMeter). 但是,当我从多个线程(使用JMeter)调用非静态成员时,会出现问题。

By example: 例如:

Thread 1: SingletonTest.getInstance().calculateResult(1,2) -> return 3 线程1:SingletonTest.getInstance()。calculateResult(1,2)->返回3

Thread 2: SingletonTest.getInstance().calculateResult(3,2) -> return 3 线程2:SingletonTest.getInstance()。calculateResult(3,2)->返回3

I think this happen because 2 threads are accessing in the same time at method and override de property called result. 我认为这是因为2个线程同时访问方法并覆盖了称为result的de属性。

You are right, the second thread is accesing the value of result set by the first thread. 没错,第二个线程正在访问第一个线程设置的结果值。

If you are modifying a value that is visible to multiple threads, you should synchronize the operation. 如果要修改对多个线程可见的值,则应同步操作。

public synchronized Integer calculateResult(int value1, int value2) {
    result = value1 + value2;
    return result;
}

This way the first thread to call the method gets a lock on the singleton, and the second thread can't access it until its finished. 这样,第一个调用该方法的线程会锁定单例,而第二个线程直到完成后才能访问它。

You should probably review the official tutorials if you are going to use concurrency, especially this . 如果您要使用并发性,那么您可能应该阅读官方教程 ,尤其是this

Your guess is correct and its happening because your shared result instance variable is not thread safe. 您的猜测是正确的并且正在发生,因为您的共享结果实例变量不是线程安全的。 Not sure why are you sharing it. 不知道为什么要分享它。 Fix code is here: 修复代码在这里:

public class SingletonTest {

    private static SingletonTest instance;

    private SingletonTest() {   
    }

    public synchronized static SingletonTest getInstance(){
        if(instance == null){
            instance = new SingletonTest();
        }
        return instance;
    }

    public Integer calculateResult(int value1, int value2) {
        Integer result = value1 + value2;
        return result;
    }
}

Try this 尝试这个

public class Singleton {

    private static Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
         return instance;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM