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)?
your synchronized block is sufficient. The JVM blocks on that call whenever the monitor for the synchronized object is held by another thread.

以上就是Synchronizing for the formal parameters in java的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准