Java memory model values synchronized and volatile

Source: Internet
Author: User

Multi-threaded access to shared variables.

First, it must be a shared variable.

Second, a variable must be shared by multiple threads

Thirdly, since multiple threads have their own working memory, each working memory has its own copy of the variable except for the original value of the shared variable in the main.

Finally, all the operations of a thread on a shared variable are made in its own working memory and cannot be read or written directly from the main memory.

The variables in the respective working memory cannot be accessed directly between the threads, and the pass of the thread variable value must pass through main memory.

Support for visibility supported at the Java language level:

Synchronized: Synchronous (atomicity), memory visibility,

Features: 1-wire threads unlocked before the update of the shared variable must be flushed to main memory.

2-wire Cheng, the value of the shared variable in the working memory is emptied, and the most recent value needs to be re-read from main memory.

These 2 features ensure that changes to shared variables before line threads unlocked are visible to other threads before the next lock is added.

The process by which threads execute mutually exclusive code:

Obtaining a mutex lock

Empty working memory

Copy the latest copy of the variable from main memory to working memory

Execute code

Refreshes the value of the changed shared variable to main memory

Release Mutex lock

Re-order

The order in which the code is written differs from the order in which it is actually executed, which is the optimization that the compiler or processor sits in order to improve program performance. This is mainly because some code reordering is more consistent with how the processor executes. Can improve the efficiency of CPU utilization.

1, compiler-optimized reordering (compiler Optimizations) is primarily a single thread that is inherently optimized without affecting the logic of the code.

2, instruction-level parallel reordering (processor optimization), many computers are multi-core processors, then this optimization allows the processor to execute multiple instructions simultaneously

3, the memory system reordering (processor optimization), the optimization of read-write cache,

Therefore, we do not necessarily follow the inherent logic when loading and executing the code.

only data dependencies prohibit command reordering.

As-if-serial

Regardless of reordering, the results of the execution of the program and the sequential execution of the code are consistent (Java compilers, runtimes, and processors will ensure that Java programs follow as-if-serial semantics on a single thread)

To illustrate:

If (Read)

{

a=b*3;

}

Results after reordering

Int temp=b*3;

If (Read)

{

Result=mid;

}

However, instruction reordering in multi-threading can cause memory visibility issues. By this example it is possible to know that reordering + can lead to unsafe data in multiple threads.

Cause the shared variable to be invisible between programs (without locking):

Cross-execution of threads.

Reordering is performed with thread interleaving.

Shared variable updated value does not update data in time between working memory and main memory

Then why did synchronized become safe?

1, sync, add a lock, add a lock can only have one thread to execute at the same time.

2, since the lock is added, there is only one thread executing the code over a period of time, then the reordering is irrelevant.

3, the characteristics of synchronized.

volatile keyword:

Volatile: implemented by adding a memory barrier and prohibiting reordering optimizations.

When a write operation is performed on a volatile variable, a store barrier instruction is added after the write operation. is to force the CPU cache to flush to main memory.

When a read operation is performed on a volatile variable, a load barrier instruction is added before the read operation. is to force the refresh of the CPU cache to the value of the main memory.

In layman's terms: the volatile variable is forced to read the value of the variable from main memory each time it is accessed by the thread, forcing it to flush into main memory when the variable is changed. This way, different threads can always see the latest value of the variable.

Does not have atomicity, there is no guarantee that only one thread at a time can modify the value of this variable.

So what is the appropriate use of the volatile keyword variable?

    1. The write operation on a variable does not depend on the current value. such as the situation is not satisfied: num++, num=num+1;
    2. The variable is not contained in an invariant that has other variables.

Volatile is more lightweight.

There are also Reentrantlock () objects referenced later by java1.5 to lock.

Private Lock lock=new Reentrantlock ();

Lock.lock ();

{

Code: generally try{}finally{}

}

Lock.unlock ();

Java memory model values synchronized and 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.