Java re-learning--synchronized and volatile

Source: Internet
Author: User
Tags finally block

Volatile: Only guarantee the visibility of shared resources, any changes are written in main memory, all threads can be seen immediately, for the new value does not depend on the old value of the case.

Synchronized: Ensures operational atomicity consistency and visibility.

The difference between volatile and synchronized:

  Volatile only causes variables to be known to other threads as soon as the value changes, and does not guarantee the sequential execution of multithreading. Instead, synchronized locks the current variable, and other threads are blocked only if the variable is accessible to the front thread.

Volatile can only implement variable visibility but does not have atomic properties, while synchronized can guarantee the change visibility and atomicity of variables.

Volatile does not cause a thread to block, and synchronized can cause a thread to block.

Volatile tagged variables are not optimized by the compiler, and synchronized tagged variables can be optimized by the compiler.

Appendix:

1. When a thread enters the synchronized method of an instance of an object, no other thread can access the method, but it can access the non-synchronous method of the object at the same time

2,the difference between Lock and synchronized--lock must be released after use, usually released in the finally block. Otherwise, if the protected code throws an exception, the lock may never be released.

Java re-learning--synchronized and volatile

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.