title: Synchronizing for the formal parameters in java
body: <p>Let's say I have a method, that is accessed by two or more threads and I want to make it thread safe.</p>
  
  <pre><code>public int getVal(int x, int y, MyClass myObj)  
  {
     int z;
  
     z = getInt(myObj);
  
     return x + y + z;  
  }
  </code></pre>
  
  <p>In this, I think we don't have to synchronize for x + y as they are primitives. </p>
  
  <p>Let's assume that <code>getInt(myObj)</code> modifies the state of myObj and that influences the value of z.</p>
  
  <p>Therefore, I will have to provide synchronization for the line <code>z = getInt(myObj);</code> 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.</p>
  
  <p>So, how would one ensure thread-safety for the line <code>z = getInt(myObj)</code>? (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). </p>
  
  <p>Assuming that MyClass cannot be made immutable, I am thinking that the following could be a solution.</p>
  
  <pre><code>synchronized(myObj)
  {
    z = getInt(myObj);
  }
  </code></pre>
  
  <p>Is it a correct solution? And, in what other ways can we ensure thread safety for  </p>
  
  <pre><code>z = getInt(myObj); (but only in case of different instances)?
  </code></pre>