Today, when learning Java Atom class, encountered this blog, saw the synchronization code block and synchronization method of the difference, previously did not realize, here is recorded.
public class CP {private int i = 0;public synchronized int synchronizedmethodget () {return i;} public int Synchronizedblockget () {synchronized (this) {return i;}}}
From the functional point of view, the above two methods are not different, can guarantee the atomic nature of the method execution time. In terms of performance, synchronization methods are more advantageous than synchronous code blocks. We use the JAVAP command provided by the JDK to view the generated bytecode.
E:\code_ Space\test\bin>javap-c cpcompiled from ' Cp.java ' public class CP {public CP (); code:0: Aload_0 1:invokespecial #10//Method java/lang/object. " <init> ":() V 4:aload_0 5:iconst_0 6:putfield #12//Field i:i 9:return Public synchronized int synchronizedmethodget (); code:0: Aload_0 1:getfield #12//Field i:i 4:ireturn public int synchronizedblockget (); code:0: Aload_0 1:dup 2:astore_1 3:monitorenter 4:aload_0 5:getfield #12 Field i:i 8:aload_1 9:monitorexit 10:ireturn 11:aload_1 12:monitorexit 13:athrow Exception table: From to target type 4 (any) any}
It is obvious to see that the number of bytes generated by using the synchronous code block is greater, while the synchronization method is very small.
Java synchronization mechanism: using synchronize block, or using synchronize method