Volatile variables in Java

Source: Internet
Author: User
Tags volatile

Synchronization and inter-thread communication:

      • Communication
        Communication refers to a message passing between two threads.
        Now that the message is being delivered, there must be a succession relationship between the receiving thread and the sending thread, and synchronization is required. Communication and synchronization are mutually reinforcing.

      • Synchronous
        Synchronization refers to controlling the order of execution between multiple threads.

How to communicate between threads:

    • Shared memory
      Shared memory means that multiple threads share the same piece of memory, the sender writes the message to memory, and the receiver reads the message from memory, thus delivering the message.
      However, this approach has the disadvantage of requiring programmers to control thread synchronization, which is the order in which threads are executed.

This approach does not really implement message delivery, but it is like passing a message from one thread to another thread.

      • Message delivery
        As the name implies, message passing refers to the sending thread passing the message directly to the receiving thread.
        Because the execution order is done by the concurrency mechanism, there is no need for the programmer to add additional synchronization mechanisms, but to declare the code that the message sends and receives.

Java Multithreaded memory model:

All threads share a piece of memory that is used to store shared variables;
In addition, each thread has its own storage space, storing its own local variables, method parameters, and exception objects.

use of volatile:

Public volatile boolean flag;

1) volatile is used in reordering (the compiler, the processor rearranging the order of execution of instructions to achieve optimal operational efficiency without altering the program execution results):

In the following cases, reordering does not occur even if there is no dependency between the two lines of code:

    • Volatile read

      • If the previous behavior of the volatile read operation is volatile read/write, the two lines do not reorder
      • The volatile read operation and its subsequent line of code do not reorder
    • Volatile write

      • The volatile write operation and its previous line of code do not reorder;
      • If the latter line of the volatile write operation is volatile read/write, the two lines do not reorder.
Volatile guarantees the memory visibility of shared variables:

When volatile modifies a member variable, the variable reads and writes more steps than the normal variable.

    • Volatile variable Write
      When a volatile modified variable is written, the variable is written directly to the shared memory, not to the thread's exclusive storage space.

    • Volatile variable Read
      When a volatile modified variable is read, it is read directly from the shared memory, not the thread-specific storage space.

By restricting read and write to volatile variables, you can ensure that the thread reads the most recent value each time, thus ensuring the memory visibility of the variable.

Volatile variables can only ensure that a long, double reads and writes "Atomicity" (volatile in other cases is not guaranteed atomicity):

Of all the types in Java, a long, double type is special, they occupy 8 bytes (64 bits), and the remaining types are less than 64 bits. In a 32-bit operating system, the CPU can read/write only 32 bits of data at a time, so there are two steps to read and write for a 64-bit long, double variable. In multi-threading, if a thread writes only the first 32 bits of a long variable, then the other thread reads the "half" variable, thus reading the wrong data.
To avoid this situation, you need to modify the long and double variables with volatile.

In fact, if a variable adds the volatile keyword, it tells the compiler and the JVM's memory model that the variable is shared across all threads, and each time the JVM reads the most recently written value and makes its newest value visible to all CPUs. So it's thread visibility that doesn't mention atomicity.

Below we use an example to show that volatile is not atomic, do not use volatile in getandoperate occasions (such occasions do not atoms, need to be locked, such as i++), only set or get the scene is suitable for volatile.
For example, you let a volatile integer increment (i++), in fact, to be divided into 3 steps: 1) Read the value of the volatile variable to local; 2) increase the value of the variable, 3) write the value of the local back, so that the other threads are visible. These 3-step JVM directives are:

mov    0xc (%r10),%r8d; Loadinc    %r8d           ; Incrementmov    %r8d,0xc (%R10); Storelock Addl $0x0, (%RSP); Storeload Barrier

Note the last step is a memory barrier.
What is a memory barrier (Barrier)?
Memory barrier is a CPU instruction. Basically, it's such an instruction: a) to ensure the order in which certain operations are performed, and b) to affect the visibility of some data (which may be the result of some instruction execution). The compiler and CPU can reorder the instructions in the same way that the output is guaranteed, allowing performance to be optimized. Inserting a memory barrier is equivalent to telling the CPU and the compiler to execute before the command must be executed before the command must be executed. Memory barrier Another effect is to force updates to a different CPU cache at a time. For example, a write barrier flushes the data written before the barrier to the cache so that any thread that attempts to read the data will get the latest value, regardless of which CPU core or CPU is executing it.

What is the relationship between memory barrier (barrier) and volatile? As mentioned in the above virtual machine directive, if your field is Volatile,java the memory model will insert a write barrier directive after the write operation, inserting a read barrier command before the read operation. This means that if you write to a volatile field, you must know: 1. Once you have finished writing, any thread that accesses this field will get the most recent value. 2, before you write, will ensure that all previous events have occurred, and any updated data values are also visible, because the memory barrier will be the previous write values are flushed to the cache.

Why volatile variables are accessed differently with different threads access to the modified result will not be the same (in most cases, it is not recommended to provide visibility with volatile variables):

The JVM has a memory allocation rollup at run time that is called the virtual machine stack, where thread stacks holds information about the runtime of threads, and when a thread accesses the value of an object, it first finds the value of the variable that corresponds to the heap memory by reference to the object, and then load the value of the heap memory variable into local memory ( Memory area allocated by the current thread), create a copy of the variable, and then the thread no longer has any connection to the object's variable in the heap memory, but instead directly modifies the value of the copy and automatically writes the variable copy back to heap memory after the modification is complete, so that the value of the heap memory changes:

Read and load: Copy variables from main memory to current working memory

Use and assign: Execute code, change shared variables

Store and write: Refresh main memory related content with working memory data

However, after read and load, if thread 1 modification to the volatile variable is not finished, thread 2 is modified, but the original value is modified, causing concurrency to occur.

Scenarios used by volatile variables:

1). Writes to a variable do not depend on the current value of the variable, or can ensure that only the value of a single-threaded update variable

2). The variable is not included in the invariant condition with other state variables

3). No lock required when accessing variables

Volatile variables in Java

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.