Soumya
Soumya

Reputation: 1420

Singleton, Thread Safety and Mutex

I was pondering over this question today. Here is a scenario which I am thinking.

Singleton Class with a method

public int addTwoNumbers(int a, int b) {
    int x = a;
    int y = b;
    int z = a + b;
    return z;
}

Thread - 1

singletonClassObj.addTwoNumbers(10, 20);

Thread - 2

singletonClassObj.addTwoNumbers(100, 200);

Now my question is what, let say Thread-1 gets executed first and calls the method. So is it possible that before the entire function gets executed by thread - 1, thread -2 calls the function and alters the values of x and y? For example, Thread -1, sends the data as 10 and 20 and before assigning the summation to variable z, thread -2 changes the values of x and y to 100 and 200, which in-turn makes thread-1 to return 300 instead of 30. To overcome this, we need to put in lock or mutex, but is this possible (without the mutex).

Upvotes: 0

Views: 427

Answers (2)

YoungHobbit
YoungHobbit

Reputation: 13402

addTwoNumbers: all the variables are local variable. They will be stored in the stack, when this method is called. Because each method creates its own stack. So the two threads will be having, two completely different stacks. So they are safe from multi threading perspective. You don't need any lock or mutex.

If you were using any objects (reference variable) which are always stored in the Heap Memory area. So would need the synchronization.

Also you might need the synchronization, when you are updated the state of the singleton object. Because that is shared among the threads.

Upvotes: 1

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31269

No, it is never possible for two or more threads to have access to the same local variables in a method.

Note though that when the variables are of reference type (they are not in your example, you are only using the primitive type int) then the objects that they point to may be accessed by different threads at the same time.

Upvotes: 1

Related Questions