In-depth understanding of the use and principles of java:2.1. Volatile

Source: Internet
Author: User
Tags volatile

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.

It is less expensive than synchronized in some cases, and this article will delve into how the inter processor is volatile at the hardware level, and through in-depth analysis can help us use volatile variables correctly.

official definition of volatile

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

Volatile variables are less expensive to use and execute than synchronized because they do not cause thread context switching and scheduling.

how volatile is implemented

So how does volatile ensure visibility?

Get the JIT compiler-generated assembly instructions from the tool under the x86 processor to see what the CPU will do when it writes to volatile.

Java code: Instance = new Singleton ();//instance is a volatile variable
Assembly Code: 0x01a3de1d:movb $0x0,0x1104800 (%esi); 0x01a3de24: lock Addl $0x0, (%ESP);

There is a second line of assembly code when a shared variable modified with a volatile variable is written , and by looking at the IA-32 architecture software Developer's Manual, thelock prefix instruction will cause two things under the multi-core processor.

    • Writes the data for the current processor cache row back to system memory .
    • This write-back operation causes invalid data to be cached on the other CPU in the memory address .

If a write is declared for a volatile variable, the JVM sends a lock prefix instruction to the processor, writing the data from the cache row of the variable to the system memory.

However, even if you write back to memory, if the other processor cache value is still old, and then perform the calculation operation will be problematic, so under multiprocessor, in order to ensure that the cache of each processor is consistent, the cache consistency protocol will be implemented.

Each processor checks to see if its cached value is out of date by sniffing data propagated on the bus , and when the processor finds that the memory address corresponding to its cache line is modified, the cache line of the current processor is set to an invalid state. When the processor modifies the data, it forces the data to be read into the processor cache from the system memory.

application Scenarios for volatile

Volatile can guarantee the visibility of shared variables, but it does not guarantee atomicity.

The biggest benefit of volatile relative to synchronized is that it has high performance in some cases and is intuitive and easy to use.

If your "code itself can guarantee atomicity", then using volatile is a good choice:

The code described here itself guarantees atomicity, which means:

1, the write operation of the variable, does not depend on the current value (that is, the current value will not be read first, and then the current value based on the change , for example, not self-increment, but assignment);

2, the variable is not contained in the invariant of other variables (this is not a good understanding, you can refer to here: http://www.ibm.com/developerworks/cn/java/j-jtp06197.html)

One of the most common volatile scenarios is a Boolean shared status flag bit, or double check lock for singleton mode

1. Status Mark Amount

123456789 volatileboolean flag = false; while(!flag){    doSomething();} public voidsetFlag() {    flag = true;}

12345678910 volatileboolean inited = false;//线程1:context = loadContext();   inited = true;             //线程2:while(!inited ){sleep() }doSomethingwithconfig(context);

2.double Check

1234567891011121314151617 class Singleton{    private volatile static Singleton instance = null;        private Singleton() {             }        public static Singleton getInstance() {        if(instance==null) {            synchronized (Singleton.class) {                if(instance==null)                    instance = new Singleton();            }        }        return instance;    }}

In addition, there is a common pit of volatile :

As can be seen from the above description, volatile is useful for basic data types (values are directly from main memory to working memory copy).

But it doesn't seem to work for the object, because volatile is just a guarantee of the visibility of the object reference, and the field inside the object doesn't guarantee anything.

Even when using threadlocal, each thread has a copy of the variable, which is stored in the heap itself, and is still a reference to the base data type and copy of the variable in the line Cheng.

In fact, if an object is modified by volatile, it means that its reference has visibility. Any changes that are made to a variable reference are thus visible between threads.

This is applied in the atomicreference that will be introduced later.

In-depth understanding of the use and principles of java:2.1. Volatile

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.