I was wondering if in Java I would get any odd behaviour if I synchronise twice on the same object?
The scenario is as follows
pulbic class SillyClassName { object moo; ... public void method1(){ synchronized(moo) { .... method2(); .... } } public void method2(){ synchronized(moo) { doStuff(); } } }
Both methods use the object and are synchronised on it. Will the second method when called by the first method stop because it’s locked?
I don’t think so because it’s the same thread but I’m unsure of any other odd results that might occur.
Reentrant
Synchronized blocks use reentrant locks, which means if the thread already holds the lock, it can re-aquire it without problems. Therefore your code will work as you expect.
See the bottom of the Java Tutorial page Intrinsic Locks and Synchronization.
To quote as of 2015-01…