Let’s suppose I have a thread that locks on an object reference
Thread #1
lock(myObj) { ... }
later in code I have myObj = new XYZObj();
and then Thread #2 locks on it
lock(myObj) { ... }
Will this code be thread safe, if the object reference has changed? When the object reference changes, the first lock is still valid?
Locks work on instances, not variables.
The
lockstatement will hold its own reference to the instance so that it will only exit the instance you entered.The spec says:
If you re-assign the variable between the two locks, you will get two valid locks on two different instances.
In general, however, you should never do that; it’s a recipe for subtle bugs and race conditions.
You should only lock on dedicated readonly lock objects.