Concurrent Programming (2) ---- volatile and synchronized (to be completed ),

Source: Internet
Author: User

Concurrent Programming (2) ---- volatile and synchronized (to be completed ),

This article mainly discusses volatile and synchronized, and introduces some basic concepts to give readers a better understanding of the two.

I. Several Related Concepts

1. atomicity

The intention is "the smallest particle that cannot be further separated", and atomic operations mean "one or a series of operations that cannot be interrupted ". It is a bit complicated to implement atomic operations with multiple processors.

1) how the operating system achieves atomicity.

A single processor can automatically perform 16/32/64-bit atomic operations on the same cache row. However, complex memory operation processors cannot guarantee their atomicity, such as cross-bus width, cross-Cache rows, and cross-page table access. For example, I ++ is a read rewrite operation. Because the code may be executed by different threads, the final result may not be what we want (the specific reason is not described here ). However, the processor provides two mechanisms: Bus lock and cache lock to ensure the atomicity of complex memory operations.

A. Use bus locks to ensure atomicity

The processor solves the I ++ problem by using bus locks. The so-called bus LOCK is a LOCK # signal provided by the processor. When a processor outputs this signal on the bus, requests from other processors will be blocked, and the processor can exclusively share the memory.

B. Use cache locks to ensure atomicity

The bus lock locks the communication between the CPU and memory, so that during the lock period, other processors cannot operate the data of other memory addresses, so the bus lock overhead is relatively large. We only need to ensure that the operation on a memory address is atomic (reduce the lock granularity ). Currently, in some cases, the processor uses cache locks instead of bus locks for optimization.

2. Visibility

Visibility means that when one thread modifies a shared variable, the other thread can read the modified value.

3. Command rescheduling

Reordering refers to a method by which the compiler and processor re-order the instruction sequence to optimize program performance. In a multi-threaded program, the re-sorting of certain commands may change the execution result of the Program (subsequent examples will be provided ).

Ii. volatile

1. volatile variables have the following features.

Visibility: The read of a volatile variable always shows the Final write to this volatile variable by any thread,

Atomicity: The read/write operations on any single volatile variable are atomic, but composite operations like I ++ are not atomic.

Disable reordering: After jdk1.5, the volatile semantics is enhanced, and the volatile variables are not allowed to be reordered.

2. Underlying implementation principle

1) Operating System Level

The operating system can use the LOCK # prefix command to implement the first two features. To improve processing speed, the processor does not directly communicate with the memory, but first reads the system memory data to the internal cache (L1, L2, or other) Before performing operations, but I don't know when to write back to the memory after the operation (the operating system actually uses asynchronous operations to solve the problem of uneven Production and Consumption speed ). If the volatile variable is declared for write operations, JVM will want the processor to send a Lock prefix command to write the data in the cached row of the variable back to the memory. In this case, the value in other processors is still the old value. In a multi-processor environment, the cache consistency protocol is implemented to ensure the cache consistency of each processor. Each processor detects whether the cached value has expired by sniffing the data transmitted on the bus. When the processor finds that the cached row has expired, the cache row of the current processor is set to invalid. When the processor modifies the data, it will re-read the data from the operating system memory to the processor cache.

A. The Lock prefix command causes the processor to write the cache back to the memory.

The Lock prefix command causes the Lock signal of the audio processor during the execution of the command. In a multi-processor environment, the processor can exclusively occupy any shared memory. The operating system uses bus locks or cache locks to ensure that only one processor can modify the cached data.

B. The cache of one processor is written to the memory, leading to invalid cache of other processors.

2) JMM layer.

In Java, all instance domains, static domains, and array elements are stored in the heap memory and shared among threads in the heap. Local variables, method-defined parameters, and exception handling parameters are not shared between threads, and they do not have memory visibility issues.

From an abstract point of view, JMM defines the abstract relationship between the thread and the main Memory: Shared variables between threads are stored in the main Memory, and each thread has a private Local Memory ), the local memory stores copies of the variable shared by the modified thread. Local memory is an abstract concept of JMM and does not exist. The JMM abstraction is as follows.

When a variable is declared as volatile.

Write operation: JMM refreshes the variables in the local memory corresponding to the thread to the primary memory.

Read operation: JMM will invalidate the local memory, and the thread will then read the shared variable from the main memory.

 

 

3) disable the re-sorting Application

In Singleton mode, dual verification is used to reduce the lock synchronization overhead and check the following code without volatile.

  

The above is an incorrect optimization. When the thread executes the code to 4th rows, the Code reads that the instance is not null, but note that the object referenced by the instance has not been initialized yet. The reasons are as follows.

Instance = new Singleton () can be divided into the following three lines of pseudo code.

Memory = allocate (); // 1. allocate the memory space of the object.

CtorInstance (memory); // 2. initialize the object

Instance = memory; // 3. Set the instance to point to the address just allocated

Steps 2 and 3 may cause another thread to access an uninitialized object due to command rescheduling. This problem can be solved by adding volatile before the instance variable.

 

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.