The synchronized of the Java keyword

Source: Internet
Author: User

1.synchronized can be used to modify a common method, or code block, this time synchronized lock is the current object, as long as there is a thread in the corresponding method or block of code, other threads must wait.
2.synchronized is valid only for modified methods, and other non-synchronized methods that lock the object are accessible.
3.synchronized can also be used to lock the specified object, and when a thread accesses the specified object, other threads attempting to access the specified object will block until the thread accesses the specified object end
4.synchronized can be used to modify a static method, the static method belongs to the class but not the object. Similarly, synchronized-modified static methods lock all objects of this class
The 5.synchronized (*.class) effect is the same as locking a static method, all objects that lock the class.

Summarize

A. Regardless of whether the Synchronized keyword is added to a method or an object, if the object it is acting on is non-static, the lock it obtains is an object, and if the synchronized object is a static method or a class, the lock it obtains is the same lock on the class, all objects of that class.
B. Each object has only one lock (lock) associated with it, and whoever gets the lock can run the code it controls.
C. Achieving synchronization is a costly overhead, and may even result in deadlocks, so avoid unnecessary synchronization controls as much as possible.

retouch Content Lock Type Example
modifying code blocks Arbitrary object Lock Example Four
Modifying a common method This lock Example Five
modifying static methods Class lock Example Six

The synchronized of the Java 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.