Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronizing for the formal parameters in java

Let's say I have a method, that is accessed by two or more threads and I want to make it thread safe.

public int getVal(int x, int y, MyClass myObj)  
{
   int z;

   z = getInt(myObj);

   return x + y + z;  
}

In this, I think we don't have to synchronize for x + y as they are primitives.

Let's assume that getInt(myObj) modifies the state of myObj and that influences the value of z.

Therefore, I will have to provide synchronization for the line z = getInt(myObj); but only when both threads to pass same instance in 'myObj' reference. As the API's coder I would not know whether both threads would pass same instance for 'myObj' or not. In some case these threads might pass same MyClass instance in 'myObj' reference and in other cases they might pass different MyClass-instances in 'myObj' reference.

So, how would one ensure thread-safety for the line z = getInt(myObj)? (Surely, we do not want to synchronize when instances passed are different and only have to synchronize when instances passed are same. I it is clear that this cannot be determined).

Assuming that MyClass cannot be made immutable, I am thinking that the following could be a solution.

synchronized(myObj)
{
  z = getInt(myObj);
}

Is it a correct solution? And, in what other ways can we ensure thread safety for

z = getInt(myObj); (but only in case of different instances)?
like image 808
Real Red. Avatar asked Mar 09 '11 19:03

Real Red.


2 Answers

What you have is correct. When you synchronize on an object its locking on that instance not on that class. So if I pass the same *instance* of an object to two different methods, it will lock on that object correctly. However, if I pass two different instance, there won't be any locking because the two instance have each their own lock.

like image 121
Amir Raminfar Avatar answered Oct 05 '22 06:10

Amir Raminfar


If getInt doesn't modify the state of this, then the method is thread-safe. The thread-safeness of the myObj object is the responsability of its class : MyClass, or of the object that holds it. Not the responsibility of all the methods which might take it as an argument, IMHO.

Your solution (synchronized(myObj)) is right, though : two threads won't be able to execute the getInt method concurrently if the same myObj is used in both threads. They will execute concurrently if the two myObjs are different.

like image 38
JB Nizet Avatar answered Oct 05 '22 06:10

JB Nizet