Learner
Learner

Reputation: 21425

Calling a method concurrently in a singleton class

Let's say I have created a singleton class called Calculator with a method add that takes 2 parameters.

public class Calculator {
    private static Calculator instance = new Calculator();

    public static Calculator getInstance() {
        return instance;
    }

    public int add(int num1, int num2) {
        return num1 + num2;
    }
}

Case 1: Now since it is singleton, will there be any issues if we call the method add concurrently say 10,000's of times?

Case 2: If this class is not singleton, and a normal class then what will happen if I do the same thing, calling it concurrently.

Case 3: Now if my class is not singleton and if my add method is a static method then how the memory will be used?

So my doubt is how it behaves, what is the Java memory model in the given scenarios. Which is efficient or recommended one? Can you please help me in understanding this?

Upvotes: 0

Views: 1445

Answers (2)

Maheshwar Ligade
Maheshwar Ligade

Reputation: 6855

There is no issue if the method called concurrently. for all your case there is no issue. There will be no concurrency issues because no state is being modified. So nothing will impact.

If want to access it in multi-threaded environment then you need to make it as synchronised to thread safe.

Upvotes: -1

Nir Alfasi
Nir Alfasi

Reputation: 53535

Case 1: Now since it is singleton, will there be any issues if we call the method add concurrently say 10,000's of times?

There is no concurrency issue here: the method add doesn't have any side-effects (it doesn't change the state of the object).

Case 2: If this class is not singleton, and a normal class then what will happen if I do the same thing, calling it concurrently.

Same answer as the previous one.

Case 3: Now if my class is not singleton and if my add method is a static method then how the memory will be used?

Same answer as the previous two: it doesn't matter if the method is static or not, every time it's called with the two parameters it will perform the calculation on these parameters without changing the state of the instance/class.

So my doubt is how it behaves, what is the Java memory model in the given scenarios. Which is efficient or recommended one? Can you please help me in understanding this?

Again, it doesn't matter. There will be no concurrency issues because no state is being modified. This has nothing to do with concurrency or with JMM.

Upvotes: 4

Related Questions