How Java uses synchronized to process multi-thread Data Synchronization

Source: Internet
Author: User

Java has the following methods to handle concurrent access to code blocks:
First, the keyword synchronized
Second, lock (Lock Object, condition object)

Java provides an internal lock for each object. After the keyword synchronized is added to the method definition, the object lock will protect the entire method. That is to say, the following two statements are equivalent:
Public synchronized void method ()
{
......
}

Public void method ()
{
This. intrinsickLock. lock ();
Try
{
......
}
Finally
{
This. intrinsickLock. unlock;
}
}

The above two methods are not recommended in Java Core!

Key words synchronized explanation:
The principle of synchronized implementation is that Java has a built-in lock for every object. For a common method of a class, synchronized locks every new object method, for example, for the following code:
Public class Test {
Public void synchronized testMethod ()
{
.......
}
}

Test obj1 = new Test ();
Test obj2 = new Test ();
If Thread-1 accesses obj1 and Thread-2 accesses obj2, neither Thread will be blocked because these are two different objects.
If Thread-1 accesses obj1 and Thread-2 also accesses obj1, Thread-2 will be blocked because the two threads access the same object, but Thread-1 gets the lock first, so Thread-2 must wait until Thread-1 releases the lock before access.

For a static method, synchronized becomes a class lock. In both cases, Thread-2 will be blocked, because static methods share all objects of the class.

In addition to locking the entire method, synchronized also locks the code block.
One method is:
Public void method ()
{
Synchronized (this)
{
....
}
.....
}
Another method is:
Object obj = new Object ();
Public void method ()
{
Synchronized (obj)
{
....
}
.....
}
The second method is more flexible. When synchronized is used, you need to be careful when using synchronized for protection, resulting in performance problems.

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.