Java synchronization mechanism: using synchronize block, or using synchronize method

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.