Atomicity and visibility of threads

Source: Internet
Author: User

 

The most basic purpose of synchronization is to ensure atomicity. Another easy-to-ignore objective is visibility, that is, the shared data modified by one thread is visible to another thread.

Some basic assignment operations are atomic. Therefore, if you do not use synchronized for these assignment operations, you can use volatile to solve the problem of visible modifications of one thread to another. So volatile is a way to avoid using synchronized for visibility while ensuring atomicity.

Private Static volatile int nextserialnumber = 0;

Public static int generateserialnumber (){
// Because the "value assignment" such as nextserialnumber ++ is actually divided into multiple steps. In this way, the following method cannot guarantee atomicity.
Return nextserialnumber ++;
}

Improvement:
Private Static int nextserialnumber = 0;
// If synchronized is used, volatile can be omitted. The latter ensures visibility.
Synchronized public static int generateserialnumber (){
Return nextserialnumber ++;
}
Or:
// Atomiclong is a cam mechanism that ensures visibility and atomicity.
Private Static final atomiclong nextserialnum = new atomiclong ();
Public static long generateserialnumber (){
Return nextserialnum. getandincrement ();
}

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.