Java violate and synchronize__ programming languages

Source: Internet
Author: User

Volatile means that this variable does not have to be optimized with local replicas to ensure that all threads directly manipulate the variables in main memory and are truly shared.

Volatile is about visibility, independent of atomic operations and thread safety.


Synchronized is often emphasized as a mutex, guaranteeing that only one thread enters. In fact, it also has the meaning of ensuring visibility, that is, the incoming thread will certainly see the previous entry of the thread's update results. If there is no synchronized, even if the variable being assigned is just an int, is an atomic operation (that is, the second thread either reads the value before the update, or reads the value after the update, does not read an intermediate state), and there is a problem with the visibility, that is, after the thread may read or the old value, There is a problem with the application logic. Why allow this, because since you do not say synchronization, the threads are completely independent of each other.


So synchronized has two layers of meaning.

1 The exclusive during the execution of the code block to ensure that the other threads do not disturb, so as to ensure the integrity of the data,

2) After the execution of the visible. Ensure that the threads that enter after the thread can see the results of the line.


Visibility, atomicity is two different 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.