Will this code be a safe thread
The lock(myObj) { ... } is safe only until a new reference to the object is bound to the variable myObj . Addition:. In addition, it is safe if any data shared between streams that are used non-atomically mutate inside an object lock, only use non-atomic mutations inside locks on the same object.
That way, every time you enter a lock for myObj , the actual reference object is what is used to lock, not your variable. If you change the variable to a link to a new object, you are actually blocking different objects in different locks, which is clearly not what you wanted. But, again, the next time you return to the first lock, the first and second lock objects can be synchronized again, and it will be safe again. May be!
As you can see, this behavior is completely broken. Is this a hypothetical question or are you really doing that?
Johann Gerell
source share