Java Concurrency base--volatile keyword

Source: Internet
Author: User
Tags visibility volatile

One, the Java memory model 1.java memory model

Temporary data in the process of running the program is stored in main memory (physical memory), but the computing power and speed of modern computer CPUs is very efficient, the speed of reading and writing data from memory can not keep up with the CPU processing speed, in this case, the CPU cache came into being. Cache-based storage interactions are a good solution to the speed of processor-to-memory conflicts, but there is a new problem: Most computers are multi-core CPUs or multiprocessor, each with its own cache, but these processors share the same main memory. The Java memory model primarily defines the access rules for variables in Java programs, where variables are not the same concept as variables in Java programming, including: Instance fields, static fields, and elements that make up an array object, but not local variables and method parameters, which are thread-private. The Java memory model specifies:

(1) All variables are stored in main memory, each thread has its own working memory, the working memory of the thread holds the variables used by the thread, and these variables are copies of the corresponding variables from the main memory

(2) All operations of a thread on a variable (read, assign) must be made in working memory, not directly read and write to the variables in main memory

(3) There is no direct access to each other's working memory between different threads, and the transfer of variable values between threads requires primary memory.

2.java working memory interaction with main memory

Lock (locked): A variable that acts on the main memory and identifies a variable as a thread-exclusive state.
unlock (Unlocked): Acts on the main memory variable, releasing a variable that is in a locked state. The released variable can be locked by another thread.
read (read): Acts on the main memory variable, transferring a variable value from main memory to the working memory of the thread. In order for subsequent load actions to use
load (load): Variables acting on working memory, It puts the value of the variable that the read operation obtains from main memory into a variable copy of the working memory.
use (use): A variable that acts on the working memory, passing a variable value in the working memory to the execution engine, This operation is performed whenever a virtual opportunity is taken to a bytecode directive that requires the value of a variable to be used.
assign (Assignment): A variable acting on the working memory that assigns a value to the working memory from the execution engine. This operation is performed whenever a virtual opportunity is assigned to a byte-code instruction that assigns a value to a variable.
store (storage): A variable acting on a working memory that transfers the value of a variable in the working memory to the main memory. For subsequent write operations.
write (write): A variable that acts on the main memory, which transfers the store operation from the value of a variable in the working memory to a variable in the main memory.

Ii. Basic Concepts 1. Visibility: The visibility of Java multithreading, where one thread modifies the state of an object that is visible to another thread. Synchronization or volatile is often used in Java to guarantee the visibility of variables. 2. Atomicity: That is, one operation or multiple operations are either fully executed and the process executed is not interrupted by any factor, or is not executed. Atoms represent indivisibility, for example: int a=0, this operation is indivisible, and conversely, a++ this operation can be cut
Can be divided into a=a+1, read the value of a in memory, read a value after adding 1 operation, the result value is written to memory. 3. Orderliness: The order in which the program executes is executed in the order of the Code. In the Java memory model, the compiler and processor are allowed to reorder instructions, but the reordering process does not affect the execution of a single-threaded procedure, but it can affect the correctness of multithreaded concurrency execution. 4. Reordering: In order to improve performance when executing a program, the compiler and processor will often reorder the instructions, and reorder them into three types:
    • The re-ordering of compiler optimizations. The compiler can rearrange the execution order of the statements without changing the semantics of the single-threaded procedure.

    • Reordering of instruction-level parallelism. Modern processors use instruction-level parallelism to overlap multiple instructions
    • reordering of memory systems. Because the processor uses the cache and read-write buffers, this makes the load and storage operations appear to be executing in a disorderly sequence
Iii. Volatile1. Basic concepts

The J-Ava language provides a slightly weaker synchronization mechanism, the volatile variable, that is used to ensure that updates to variables are notified to other threads. When a variable is declared as a volatile type, the compiler and the runtime will notice that the variable is shared, so the operation on that variable is not reordered with other memory operations. Volatile variables are not cached in registers or in places that are not visible to other processors, so the most recent write value is always returned when reading a variable of type volatile. When reading and writing non-volatile variables, each thread first copies variables from memory to the CPU cache. If the computer has multiple CPUs, each thread may be processed on a different CPU, which means that each thread can be copied to a different CPU cache. While declaring variables to be volatile, the JVM guarantees that each read variable is read from memory, skipping the CPU cache step.

2. Basic use
1  Public classdoublecheck{2 3     Private Static volatileDoublecheck instance;4 5     PrivateDoublecheck () {}6 7      Public StaticDoublecheck getinstance () {8 9         //First time detectionTen         if(instance==NULL){ One             //Sync A             synchronized(Doublecheck.class){ -                 if(Instance = =NULL){ -                     //where problems can occur in a multithreaded environment theInstance =NewDoublecheck (); -                 } -             } -         } +         returninstance; -     } +}

The code above is a classic single-instance double-detection code that does not matter in a single-threaded environment, but it can be a thread-safe issue in a multithreaded environment. The reason is that when a thread executes to the first detection and the read-instance is not NULL, the instance reference object may not be initialized, and the non-thread-safe problem can be resolved well after the volatile modification.

3. Summary

, to ensure that this variable is visible to all threads, here "visibility", as described at the beginning of this article, when a thread modifies the value of this variable, volatile guarantees that the new value can be immediately synchronized to the main memory and immediately refreshed from the main memory before each use

②, prohibit command reordering optimization. A variable with a volatile modifier, after which the assignment performs a "Load Addl $0x0, (%ESP)" operation, which is equivalent to a memory barrier (the command reordering cannot reorder the subsequent instructions to the memory barrier), and only one CPU accesses the memory. No memory barriers required

The read performance consumption of and volatile is almost identical to the normal variable, but the write operation is slightly slower because it requires inserting many memory barrier directives in the local code to ensure that the processor does not occur in a disorderly sequence.

④,volatile variables, are essentially through the memory barrier to achieve their visibility and prohibit rearrangement optimization. The memory barrier is the hardware layer concept, the different hardware platform implements the memory barrier the means is not the same, Java by shielding these differences, unifies by the JVM to generate the memory barrier the instruction. The memory barrier has two functions: to prevent command reordering on both sides of the barrier, forcing the write buffer/cache of dirty data to be written back to main memory, so that the corresponding data in the cache is invalidated.

Java Concurrency base--volatile keyword

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.