Java Concurrency programming 2_ thread Safety & memory model

Source: Internet
Author: User

"You never know when a thread is running!" “

In the previous blog Java concurrent programming 1_ multi-Threading implementation, we see that the results of the program running in multiple threads are often uncertain and inconsistent with our expected results. This is the thread's insecurity. Thread security is very complex, and without any synchronization, the order of execution of multithreading is unpredictable. Thread safety issues occur when multiple threads access the same resource. For example, there is a bank account, a thread to the inside of the money, a thread to withdraw money, if you get an uncertain result that is how terrible things.

Introduced:

For example, the following program, under a single thread, executes two times i++ the final value of the theoretical I is 12, but the result cannot be determined in a multithreaded environment.

public class Test implements runnable{private int i = 10;private void increase () {i++;} @Overridepublic void Run () {increase ();} public static void Main (string[] args) {Test t = new Test (); thread T1 = new Thread (t); Thread t2 = new Thread (t); T1.start (); T2.start (); Thread.yield (); System.out.println (T.I);}}

Ran 4 times, resulting in 10 or 11 or 12. The result of the operation is not deterministic at all.


Just a simple operation that performs a i++ can result in confusing results in a multithreaded environment.

The following will analyze thread safety from the thread's mechanism/java thread memory model.

The mechanism of the thread:

By using a multithreaded mechanism, each of these separate tasks (subtasks) is driven by the execution thread. A thread is a single sequential control flow in a process, so a single process can have multiple concurrent tasks. Each task in the program seems to have its own CPU, and the underlying mechanism is to slice the CPU time.

When a thread is used, the CPU shifts the time it takes for each task to allocate it. Each task feels like it has been occupying the CPU, but in fact CPU time is divided into fragments assigned to all tasks. (multiple CPUs or multi-core exceptions).

Java Thread memory Model:

Java Virtual machine defines a Java memory model that masks memory access differences between each hardware and operating system to achieve the same memory access on different platforms. (This is also the reason for Java cross-platform)


The memory model of the thread specifies that all variables are stored in main memory (which is what we call heap memory), and each thread has its own working memory. The working memory holds a copy of the live memory of the variable used by the thread. All the actions of a thread on a variable must be made in working memory and not directly read and written to the variables in main memory. Different threads cannot directly access variables in the other's working memory. The transfer of variable values between threads needs to be done through main memory.

How do variables copy from live memory to working memory/How to sync from working memory to main memory? The Java memory model defines 8 operations: Lock/unlock/read/load/use/assign/save/write.

L A Use Action (BYA thread) transfers the contents of the thread ' s working copy of A variable tothe thread ' s execution en Gine.

L An Assign action (by a thread) transfers a value from the thread's execution engine into Thethread ' s working copy of a V Ariable.

L A read action (bythe main memory) transmits the contents of the master copy of A variable to Athread ' s working memory F Or use by a later load operation.

L A Load action (BYA thread) puts A value transmitted from main memory by A read action into Thethread ' s working copy of A variable.

L A Save action (by a thread) transmits the contents of the thread's working copy of a Variableto main memory for use by a Later write operation.

L A Write action (by the main memory) puts a value transmitted from the thread's working memoryby A store action into the Master copy of a variable in main memory.

Java Threading and Memory interaction


The 8 operations are atomic/non-double/long (exceptions are available on some platforms), and the Java Virtual machine also provides a set of operational rules.

(1) Read and load, store and write must appear in pairs, do not allow a single operation, otherwise it will cause the value read from the main memory, the working memory is not accepted or the work memory initiated write operations and the main memory unacceptable phenomenon.

(2) The assign operation in the thread changes the copy of the variable, then the copy must be synchronized back to main memory via Store-write. If the assign operation does not occur in the thread, then it is not allowed to use Store-write to synchronize to main memory.

(3) Load and assign operations must be carried out before the use and store operations are applied to a variable.

(4) The variable can only allow one thread to lock it at the same time, and how many times the lock operation must have unlock operation.

(5) After the lock operation, the original copy of the variable in working memory is emptied, and the new value needs to be read-load from the main memory again.

(6) Before performing the unlock operation, it is necessary to synchronize the changed copy back to main memory.

Three features of Java memory:

1. atomicity: Ensure that they are treated as non-divided operations to manipulate memory without a context switch (switch to another thread). Atomic operations can be guaranteed to be non-interruptible by the threading mechanism. To ensure a wider range of atomicity, you can use the Synchronized keyword (also called a sync lock, corresponding to the bytecode directive monitorenter/monitorexit) in your code. (The code between synchronized is atomic??) Doubt

2. Visibility: Refers to a thread that modifies the value of a shared variable, and other threads can immediately know the change. The Synchronized keyword guarantees visibility. The above rule (6) guarantees this. In addition, the volatile keyword also has the same effect.

Visibility to ensure that a thread can see the execution results of another thread in a predictable way. (that is, when thread B executes a lock-protected synchronization code block, you can see all the operation results (Happens-before relationships) in the same synchronized code block before thread A.) Lock to ensure visibility as


3. Ordering: The JMM (Java memory model, Java storage models) does not guarantee that threads are in the same order that they are seen by other threads when they occur on variable operations. JMM allows threads to store variables in main memory in the order in which they are written. Compilers and processors may be reordered for performance optimizations

Another function of the volatile keyword is to prevent the compiler from being optimized to prevent reordering. The following isthe V olatile, in detail on the reordering phenomenon.

The characteristics of Java threading Mechanism and JMM determine the uncertainty in the process of multithreading, so it is necessary to thread synchronization to ensure thread security. Next blog detailed synchronized keywords.

Java Concurrency programming 2_ thread Safety & memory model

Related Article

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.