Curruncy Develop base

Source: Internet
Author: User

Volatile is a variable modifier, and synchronized is a modifier of a method or block. So we use both of these keywords to specify three simple ways to access variables.

int i1; int Geti1 () {return i1;}

volatile int i2; int Geti2 () {return i2;}

int i3; synchronized int Geti3 () {return i3;}

============= about the difference between the two ===================

The 1.volatile is essentially telling the JVM that the current variable's value in the register (working memory) is indeterminate and needs to be read from main memory, synchronized is the current variable, and other threads are blocked if the line can access the variable.
2.volatile can only be used at variable levels; Synchronized can be used at variable, method, and class level
3.volatile can only realize the modified visibility of variables, not guarantee atomicity, and synchronized can guarantee the modification of variables visibility and atomicity
4.volatile does not cause a thread to block; synchronized can cause threads to block.
5.volatile-tagged variables are not optimized by the compiler; synchronized-tagged variables can be optimized by the compiler

The red font part is for the following reasons:
Thread A modifies the variable before it is finished, and another thread B can see the modified value and can modify the variable without waiting for a to release the lock because the volatile variable is not locked

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.