The underlying implementation of the Java synchronized keyword

Source: Internet
Author: User

Each object has a lock (monitor, monitor Lock), the class object also has the lock, if the Synchronized keyword decorates the synchronization code block, through the anti-compilation can see, actually has a monitorenter and monitorexit instruction, namely, A thread must first obtain the monitor lock on the object in order to enter the synchronization code block, and if the other thread also acquires a lock on the object, it will block until the current thread releases the monitor lock. Synchronized (this) is the lock of the current object, and synchronized (A.class) is the lock class object.

If the Synchronized keyword modifies the normal method, the thread must first obtain the object's lock before calling the object's synchronization method, which is blocked if other threads are also calling other synchronization methods of the object. If the Synchronized keyword modifies the static method, because the static method belongs to the class, you must first obtain a lock on the class object.

By anti-compilation You can see that the Synchronized keyword is added before the method, essentially adding a

Acc_synchronized (Access SYNCHRONIZED) flag, when the method is called, first checks whether the method's acc_synchronized is set, and if set, the execution thread will first get the object's monitor lock, The method body can be executed after the method has been successfully executed before releasing monitor. No other thread can get the monitor lock on the object during the execution of the method.

The Synchronized keyword resolves atomicity (non-disruptive, mutex), visibility (guaranteed to be modified even if visible), and consistency issues (preventing reordering).

The underlying implementation of the Java synchronized keyword

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.