Synchronized usage in Java

Source: Internet
Author: User

1. When synchronized is used as a function modifier
Public synchronized void methodaaa ()
{< br> //....
}< br> It is equivalent to
Public void methodaaa ()
{< br> synchronized (this) // (1)
{< br> //.....
}< BR >}< br> it locks the object that calls the synchronization method.

2. Synchronization block, for exampleCodeAs follows:
Public void method3 (someobject so)
{
Synchronized (SO)
{
//.....
}
}
When a specific object is used as a lock, you can write it like this.ProgramBut when there is no clear object as the lock, just want to synchronize a piece of code, you can create a special instance variable (it must be an object) to act as the lock:
Class Foo implements runnable
{
Private byte [] Lock = new byte [0]; // special instance variable
Public void methoda ()
{
Synchronized (LOCK ){//... }
}
//.....
}
Note: creating a zero-Length byte array object is more economical than any other object-view the compiled bytecode: only three operation codes are required for generating a zero-Length byte [] object, object lock = new object () requires seven lines of operation code.
3. apply synchronized to the static function. The sample code is as follows:
Class foo
{
Public synchronized static void methodaaa () // synchronized static function
{
//....
}

Public void methodbbb ()
{
Synchronized (FOO. Class) // class literal (Class Name literal constant)
}
}

the methodbbb () method in the Code uses class literal as the lock. It produces the same effect as the synchronized static function, and the obtained lock is very special, is the class of the object currently calling this method (class, instead of a specific object generated by this class ).

Related Article

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.