Pregunta

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).

By example:

Thread 1: SingletonTest.getInstance().calculateResult(1,2) -> return 3

Thread 2: SingletonTest.getInstance().calculateResult(3,2) -> return 3

I think this happen because 2 threads are accessing in the same time at method and override de property called result.

¿Fue útil?

Solución

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.

Otros consejos

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;
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top