Introduction:
Synchronized and volatile play an important role in multithreaded concurrent programming, and volatile is a lightweight synchronizedthat guarantees the "visibility" of shared variables in multiprocessor development.
Visibility means that when a thread modifies a shared variable, another thread can read the modified value.
official definition of volatile
The definition of volatile in the third edition of the Java Language specification is as follows: The Java programming language allows threads to access shared variables, and in order to ensure that shared variables can be updated accurately and consistently, the thread should ensure that the variable is obtained separately through an exclusive lock. The Java language provides volatile, which in some cases is more convenient than a lock. If a field is declared as a Volatile,java thread, the memory model ensures that all threads see that the value of this variable is consistent.
Why use volatile?
The volatile variable modifier, if used appropriately , is less expensive to use and execute than synchronized because it does not cause thread context switching and scheduling.
use optimization for volatile
The famous Java concurrency programmer, Doug Lea, adds a queue collection class LinkedTransferQueue in the concurrency package of JDK7, where he uses a volatile variable to optimize the team's performance by appending a byte.
Additional word energy-saving optimized performance? This approach looks magical, but understanding the processor architecture will understand the mysteries. Let's take a look at the LinkedTransferQueue class, which uses an inner class type to define the queue's head queue (head) and tail node (tail). And this inner class paddedatomicreference does only one thing with respect to the parent class Atomicreference, appends the shared variable to 64 bytes. We can calculate that a reference to an object takes up 4 bytes, it appends 15 variables to a total of 60 bytes, plus the parent class's value variable, altogether 64 bytes.
Use of high concurrency synchronous volatile in Java