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