Synchronizing on an object in java, then changing the value of the synchronized-on variable

后端 未结 4 543
误落风尘
误落风尘 2020-12-11 00:41

I came across a code like this

synchronized(obj) {

   obj = new Object();

}

Something does not feel right about this , I am unable to ex

4条回答
  •  有刺的猬
    2020-12-11 00:51

    This is a case where someone might think what they are doing is OK, but it probably isn't what they intended. In this case, you are synchronizing on the current value in the obj variable. Once you create a new instance and place it in the obj variable, the lock conditions will change. If that is all that is occurring in this block, it will probably work - but if it is doing anything else afterwards, the object will not be properly synchronized.

    Better to be safe and synchronize on the containing object, or on another mutex entirely.

提交回复
热议问题