reassign synch object from within synchronized clause?
I'm curious what the effects of the following would be:
Object mutex;
... // mutex initialized in constructor etc.
public setMutex(Object mutex) {
synchronized(this.mutex) {
this.mutex = mutex;
}
}
I've seen similar questions posed with advice against doing this kind of thing in other languages but, nothing specifically for Java. I've also seen lots of questions about why one would possibly want to do this as it is seemingly self defeating code.
My rationale is that other cri开发者_如何学运维tical sections of my code may be using the mutex when setMutex() is called and I don't want the mutex reassigned until those critical sections have exited. So its not so much about guarding against race conditions on setting the mutex as it is maintaining the integrity of what the mutex is protecting. I hope that makes sense :)
Personally I think it should work just fine, but I really don't know.
EDIT: removed the "synchronized" keyword from the method signature...musta brainfartet while I was typing.
Thats really dangerous. First this synchronized block doesn't change it's behaviour at all.
Another thread that is using this synchronized block (or another based on this.mutex), will probably synchronize on another instance, but may not depending on whether or not the thread cached the this.mutex field.
See volatile
I don't think this serves any meaningful purpose. Everybody who is waiting on the old value of the "mutex" field to enter monitor will still be waiting on the original object and the new arrivals will wait on the new value.
Don't understand why the value of your synchronization primitive would ever need to change.
精彩评论