The relationship between the JVM's main memory and the working memory

Source: Internet
Author: User
Tags visibility volatile
Java Thread Memory Analysis

Reprinted from Blog http://blog.csdn.net/zhuyijian135757/article/details/51335121

Interaction diagram between threads, working memory, and main memory:

Key Edeas All threads share main memory each thread has its own working memory refreshing local memories To/from main memories must comply to JMM rules

reasons for thread safety

The working memory of a thread is an abstract description of the CPU's registers and caches: Now the computer, the CPU in the calculation, not always read from memory, its data reading order priority is: Register-cache-memory. The thread consumes the CPU, the thread calculates the raw data from the memory, during the calculation, some data may be read frequently, the data is stored in registers and caches, when the thread is calculated, the cached data should be written back to memory when appropriate. Multi-threaded concurrency problems arise when multiple threads read and write to one memory data at the same time, involving three features: Atomicity, ordering, and visibility. This is a problem for platforms that support multithreading, and languages that support multithreading on multithreaded platforms should provide a solution to the problem.

The JVM is a virtual computer, it will also face multi-threaded concurrency problems, Java programs run on the Java Virtual Machine platform, Java programmers can not directly control the underlying thread to register cache memory synchronization between, then Java from the syntactic level, should provide developers with a solution, This scheme is such as synchronized, volatile, lock mechanism (such as synchronization block, ready queue, blocking queue) and so on. These programs are only grammatical, but we need to understand them in nature;

Each thread has its own execution space (that is, working memory), the execution of the thread to use a variable, the first to copy the variables from the main memory of their own working memory space, and then the variables to operate: Read, modify, assignment, and so on, these are in the working memory is completed, and then write the variables back to the main memory;

Each thread obtains data from main memory, the data between threads is not visible; For example, the main memory variable A has a raw value of 1, thread 1 takes the variable a from main memory, modifies A's value to 2, and thread 1 does not write the variable a back to main memory, and threads 2 Gets the value of variable A is still 1;

This leads to the concept of "visibility": When a shared variable has a copy in the working memory of multiple threads, if a thread modifies the copy value of the shared variable, then other threads should be able to see the modified value, which is the problem of multi-threaded visibility.

Normal variable situation: If thread a modifies the value of an ordinary variable and then writes back to the main memory, another thread B reads the thread A after the write-back is completed, and then the value of the new variable is visible to threads B;

How to ensure thread safety
Writing thread-safe code is essentially managing access to States (state), and is often a shared, mutable state. The state here is the variable of the object (static variable and instance variable)
The premise of thread safety is whether the variable is accessed by multiple threads, ensuring that the thread security of the object requires synchronization to coordinate access to its mutable state, and that if this is not done, it can result in dirty data and other unexpected consequences. Whenever more than one thread accesses the given state variable, and one of the threads writes to the variable, synchronization must be used to reconcile the thread's access to the variable. The primary synchronization mechanism in Java is the Synchronized keyword, which provides an exclusive lock. In addition, the term "synchronization" also includes volatile variables, showing the use of locks and atomic variables.
In the absence of proper synchronization, if multiple threads access the same variable, your program has a hidden problem. There are 3 ways to fix it:
L do not share variables across threads;
L make the state variable immutable;
L use synchronization in any access state variable.

Volatile requires the program to each modification of the variable, all write back to the main memory, so that the other threading courseware, to solve the problem of visibility, but does not guarantee the consistency of the data; Special note: Atomic operations: Depending on the Java specification, the assignment or return value operation for the base type is atomic. But the basic data types here do not include long and double because the JVM sees the basic storage unit is 32 bits, and long and double are represented by 64 bits. So it can't be done in one clock cycle.

In layman's terms, the state of an object is its data, stored in a state variable, such as an instance field or a static domain, whenever more than one thread accesses a given state variable. And one of the threads writes to the variable, and synchronization must be used to coordinate the thread's access to the variable;

Sync Lock: Each Java object has only one synchronization lock, and at any given time, only one thread is allowed to have this lock.

When a thread attempts to access a block of code with the synchronized (this) tag, it must obtain the lock of the object referenced by the This keyword, which has a different fate in the following two cases.
1, if the lock is already occupied by other threads, the JVM will put this thread into the lock pool of this object. This thread goes into a blocking state. There may be many threads in the lock pool, and when other threads release the lock, the JVM randomly pulls a thread out of the lock pool, causes the thread to have the lock, and goes to the ready state.
2, if this lock is not occupied by other threads, this thread will get the lock and begin to execute the synchronous code block.
(in general, synchronization locks are not released when you execute a synchronous code block, but there are special cases where object locks are released
If an exception is encountered while executing a synchronous code block, the lock is freed, and when the code block executes, the wait () method of the object to which the lock belongs is executed, which frees the object lock and enters the object's waiting pool.

The Synchronized keyword guarantees data read-write consistency and visibility, but he is a blocking thread-control method that all other threads cannot use during the keyword use, which leads to a requirement to control thread safety called non-blocking synchronization.

ThreadLocal parsing

As the name implies, it is local variable (thread local variable). Its function is very simple, that is, each thread that uses the variable provides a copy of the value of a variable, and each thread can independently change its own copy without conflicting with the other thread's copy. From a thread's point of view, it's as if every thread has exactly the variable.

Each thread maintains an implicit reference to a copy of its thread's local variables, as long as the thread is active and the ThreadLocal instance is accessible, and all copies of its thread-local instances are garbage collected after the threads have disappeared (unless there are other references to those replicas)

You can also refer to the blog:

http://blog.csdn.net/sc313121000/article/details/40266531

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.