Java Concurrent Programming 2_ thread safety & memory model __ios

Source: Internet
Author: User
Tags visibility volatile

"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 multithreading 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 execution order 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 the result of uncertainty that is how terrible things.

Introduced:

For example, the following program, in a single thread, will sequentially print 0-9, but in a multithreaded environment you cannot have a definite result.

public class Test implements Runnable {
	private int i = 0;

	private int GetNext () {return
		i++;
	}

	@Override public
	void Run (i<) {
		System.out.println (
			getNext ());			
		}
	
	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 ();
	}

Run 2 times, the results are not correct, the results of the operation is not sure.

Just perform a i++ simple operation, in a multithreaded environment will appear inexplicable results.

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

The mechanism of the thread:

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

When using threads, the CPU rotates the time it takes to assign each task. Each task feels like it has been hogging the CPU, but in fact CPU time is divided into fragments allocated to all tasks. (Multiple CPUs or multi-core exceptions).

Java Thread memory Model:

A Java memory model defined by the Java Virtual machine masks memory access differences between hardware and operating systems to achieve the same memory access effect on different platforms. (This is also the reason for Java cross-platform)

The thread's memory model stipulates that all variables are stored in main memory (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 operations of a thread on a variable must be done in working memory, not directly in the main memory. Different threads cannot directly access variables in each other's working memory. The transfer of variable values between threads needs to be done through main memory.

How variables are copied from live memory to working memory/How to sync from working memory to main memory. The Java memory model defines the operation in 8: 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 Executio N Engine.

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

L A read action (bythe main memory) transmits the contents of the master copy of A variable to Athread ' s working memo Ry for 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 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 Thread and memory interaction

These 8 operations are atomic/Double/long (with exceptions on some platforms), and the Java Virtual machine also provides a set of operating rules.

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

(2) When a assign operation is used to change a copy of a variable in a thread, the copy must be synchronized back to the main memory via Store-write. If the assign operation does not occur in the thread, it is not allowed to synchronize to main memory using Store-write.

(3) The load and assign operations must be carried out before the use and store operations are carried out on a variable.

(4) variable at the same time only allow a thread to lock it, how many times the lock operation, you must have how many times unlock operation.

(5) The original copy of the variable in working memory is emptied after the lock operation, and new values are read-load from the main memory.

(6) The changed copy should be synchronized back to main memory before performing the unlock operation.

Three features of Java memory:

1. atomicity: Guarantee that they will be treated as an operational memory without context switching (switching to another thread). Atomic operations can be guaranteed by the threading mechanism to be uninterrupted. To ensure a larger range of atomicity, you can use the Synchronized keyword (also known as a sync lock, and corresponding bytecode instruction Monitorenter/monitorexit) in your code. A set of statements is executed as an indivisible unit. Any thread that executes a synchronized block of code cannot see that another thread is executing a synchronized block of code that is protected by the same lock.

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

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

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

Another function of the volatile keyword is to prevent compiler optimizations and prevent reordering. Later on volatile, 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 synchronize threads to ensure thread security. Next blog detailed synchronized keyword.

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.