While discussing a Java synchronization question, someone made a comment that the following snippets are not equivalent (and may compile to different bytecodes):
public synchronized void someMethod() { //stuff }
and
public void someMethod() { synchronized (this) { //stuff } }
Are they equivalent?
They are equivalent in function, though the compilers I tested (Java 1.6.0_07 and Eclipse 3.4) generate different bytecode. The first generates:
The second generates:
(Thanks to ASM for the bytecode printing).
So the difference between them persists to the bytecode level, and it’s up to the JVM to make their behavior the same. However, they do have the same functional effect – see the example in the Java Language Specification.
It should be noted, that if the method is overridden in a subclass, that it is not necessarily synchronized – so there is no difference in that respect either.
I also ran a test to block a thread trying access the monitor in each case to compare what their stack traces would look like in a thread dump, and they both contained the method in question, so there is no difference there either.