The difference and connection between volatile and synchronized

Source: Internet
Author: User
Tags modifier visibility volatile

This may be the best contrast to the volatile and synchronized effects of the article. Volatile is a variable modifier, and synchronized is a modifier of a method or a 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;
}

Geti1 () Gets the value in the I1 variable immediately in the current thread . A thread can get a local copy of a variable, and the value of the obtained variable is not necessarily the same as the value obtained by the other thread. In particular, if other threads modify the value of I1, the I1 value obtained by the front-thread may differ from the modified value. In fact, Java has a mechanism for main memory that uses one main memory to hold the correct value of the variable. Threads copy the values of variables into their own separate memory, and the memory copies of these threads may differ from the values in main memory. So in fact, this can happen, in the main memory I1 value is 1, thread 1 and thread 2 have changed i1, but did not pass the updated value back to the main memory or other threads, then it is possible that the value of I1 in thread 1 is 2, the value of I1 in Threads 2 is 3.

On the other hand, GETI2 () can effectively get the I2 value from main memory. A variable of type volatile does not allow a thread to copy the value of a variable from the main memory to its own storage space. Therefore, a variable declared as a volatile type will get the data synchronously in all threads, regardless of whether you change the variable in any thread, and the other thread will get the same result immediately. Volatile type variables are performance-intensive because they are more efficient in accessing or changing their own copies of data.

So if the volatile variable already allows the data to be synchronized between threads, then what is synchronizes used for? There are two differences in both. First, synchronized acquires and releases a lock controlled by the listener, and if two threads use a listener (that is, the same object lock), then the listener can force only one thread at a time to handle the block of code, which is the most common synchronization. In addition, the synchronized can also synchronize the memory. In practice, synchronized causes all thread memory to be in sync with the main memory. So Geti3 () executes the following process:

1. Thread gets the lock of the object from the listener. (This assumes that the listener is not locked, otherwise the thread will only get the object lock until the listener is unlocked)

2. Thread memory updates all variables, which means that he will read the variables in main memory to make sure that his variables are valid. (The JVM uses a "dirty" flag to optimize the process so that only "dirty" flag variables are updated.) Detailed case query for Java specification 17.9)

3. The code block is executed (in this example, the return value is the current value of the i3 that has just been reset from main memory. )

4. Any change to the variable will be written back to main memory. But in this case, Geti3 () doesn't change much.

5. Thread frees the object's lock to the listener.

So volatile can only synchronize the value of a variable between the thread memory and the main memory, while synchronized synchronizes the values of all variables between the thread memory and the main memory, and is implemented by locking and releasing the listener. Obviously, synchronized is more expensive than volatile in performance.

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

1.volatile essentially tells the JVM that the value of the current variable in the register (working memory) is indeterminate and needs to be read from main memory, while the synchronized is locking the current variable, and other threads are blocked only if the variable is accessible by the front-thread;
2.volatile can only be used at variable levels; Synchronized can be used at variable, method, and class levels;
3.volatile can only realize the change visibility of variables, not guarantee atomicity, while synchronized can guarantee the change of the variable visibility and atomicity;
4.volatile does not cause thread blocking; Synchronized may cause thread blocking;
5.volatile tagged variables are not optimized by the compiler; Synchronized tagged variables can be optimized by the compiler.

The Red Font section is for the following reasons:
Thread A modifies the variable before it ends, 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 unlocked

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.