views:

76

answers:

3

Hi Guys

Just curious to know (in as much detail as possible), why is it a bad practice to modify the object while using it as a lock.

//Assuming the lockObject is globally available
    synchronized(lockObject){
        lockObject.someMutativeOperation(...);
    }

Cheers

+2  A: 

Thats not bad practice, thats good practice. Where did you hear otherwise?

If you're using primitive synchronization, you synchronize on an object (or another lock) before you modify it.

It depends on the scope of the object though. If the object is scoped outside of your class, you should use a different synchronization mechanism

Kevin
+3  A: 

I don't know that I've ever heard that assertion. Certainly it would be bad to reassign lockObject (because then you'd be locking on a different object elsewhere), but I don't see anything wrong with mutating it.

Furthermore, it is fairly common to have a synchronized method which mutates an object:

public synchronized void setSomething(int something) {
    this.something = something;
}

In this case, the object itself is used as the lock. What is the point in synchronizing on a separate object?

Michael Myers
The point is to prevent deadlocks - other classes might be synchronizing on "the object itself", without your knowledge.
matt b
+2  A: 

I guess what you have heard about is mutating the reference:

synchronized (thing) {
    ...
    thing = newThing;
    ...
}

This usually indicates an error. It should probably have locked using a reference that does not change. I think it was Bitter Java that had a bug of this nature in a read-write lock (there is has been a read-write lock in the Java library for five years, so the specific implementation is no longer necessary).

Tom Hawtin - tackline