1 memory visibility of Java threads

Source: Internet
Author: User

The visibility of Java memory

Visibility: A thread changes the shared variable to be seen by other threads in a timely manner

Shared variables: If a variable has a copy in the working memory of multiple threads, then this variable is a shared variable for these threads

Java Memory Model (JMM): describes access rules for various thread- sharing variables in Java programs, as well as storing thread- shared variables in memory and reading threads shared variables from memory in the JVM The underlying details like this

The above rules are all shared variables for threads, and the details of JMM will be written in a later blog post. This article only needs to know

    • 1 All of the variables are stored in main memory
    • 2 Each thread has its own independent working memory, which holds a copy of the variable used by the thread, primarily for shared variables

The following diagram shows the main memory, working memory (also called local memory), thread, and the relationship between shared variables

By:

1 each thread has its own worker thread

2 Each thread can operate only its own working memory and cannot directly manipulate the main memory

3 Each thread has a copy of the variable A in main memory, so variable A is called a shared variable of three threads

Before you tell the variables in-memory visibility, look at the two rules in JMM (Java memory model)

1 All operations of a thread on a shared variable must be in its own working memory and cannot be read and written directly from main memory

2 variables in the working memory of other threads cannot be accessed directly between different threads, and the transfer of variables between threads needs to be done through main memory

These two rules can also be seen from the above figure.

The principle of shared variable visibility implementation

Q: How do thread 1 modifications to shared variables be seen in a timely manner by thread 2? The following 2 steps are mainly

    • Flush the updated shared variable A in the worker thread in thread 1 to main memory
    • Updates the value of the most recent shared variable A in main memory to the working memory of thread 2

After the two steps above, thread 1 modifies the shared variable and updates it to main memory in a timely manner.

Thread 2 Refreshes the value of the most recent shared variable in main memory into its own working memory

Thread 1 and Thread 2, the value of a is the same, is the latest, it is said that the shared variable a thread 1 and 2 is visible.

Because of the two rules of JMM above, threads are manipulating variables in their own worker threads, threads cannot interact directly with main memory, and threads must interact with main memory

In multithreaded programming, the following two scenarios occur:

    • Thread 1 modifies the value of the shared variable, but the value that thread 2 reads is not up-to-date when it is not updated in the main memory in a timely manner.
    • Thread 2 modifies and updates the value of the shared variable in a timely manner, but thread 2 does not read it in a timely manner, causing the thread to read to a value that is not up-to-date.

The resulting shared variable A is not visible in threads 1 and 2, and ideally, we want to implement a shared variable for all threads that access it.

Invisibility often leads to a number of serious problems that result in inconsistencies in the data. In multithreaded programming, to ensure the visibility between threads

How can I achieve the visibility of shared variables? to achieve the visibility of shared variables, two points must be guaranteed:

    • The value of a thread-modified shared variable can be flushed from the working memory to the main memory in time
    • Other threads can update the current value of shared variables from main memory to their working memory in time

What are the implementations of the visibility that Java supports at the language level?

    • Synchronized
    • Volatile

1 synchronized achieve visibility.

Two effects of synchronized:

1 atomicity (synchronous)

2 visibility

Many classmates to the first kind of synchronized synchronization comparison understanding, all know. Also often used, in fact, synchronized can also achieve the visibility of memory.

JMM two provisions on synchronized:

    • The current value of the shared variable must be flushed to main memory before the line threads unlocked
    • Line Cheng, the value of the shared variable in the working memory is emptied, and the value of the shared variable is re-read from main memory (note: Locking and unlock need to be the same lock)

The above two rules ensure that changes to shared variables before line threads unlocked are visible to other threads the next time the lock is added

The process by which the synchronized thread executes the mutex code is as follows:

1 at the entrance to the synchronized, obtain the mutex lock

2 after obtaining the mutex, empty the working memory

3 Copy the latest value of the variable from main memory to working memory

4 Code Execution

5 When the code is executed, the value of the shared variable may change, and the value of the shared variable is flushed to main memory

6 Release Lock

Before you demonstrate the code, you should know an event

Q: Must the execution order of the program be executed in the order in which the code is written?

Answer: Yes. That is not necessarily done in the order in which the code is written, mainly because the compiler or processor is optimized, that is, the order reordering

Q: Why do I have to reorder? What are the benefits of reordering?

A: The compiler or processor is optimized to improve the performance of the program, which is more consistent with processor execution efficiency.

Q: Does order reordering not disrupt the logic of the program?

A: No, because JMM has a rule, the as-if-serial principle, that is, to ensure that in a single thread, the command reordering before and after reordering, the results of execution are consistent.

As in the following example, the assignment order of a, B is different, but does not affect the value of sum, note: It is inside a single thread.

Before reordering: After reordering:

A = 1 B = 1

b = 1 A = 1

sum = a + b sum = a + b

instruction reordering: the order in which code is written differs from the order in which it is actually executed, which is the compiler or processor's optimization to improve program performance

    • Compiler-Optimized reordering (compiler Optimizations)
    • Instruction-level parallel reordering (processor optimizations)
    • Reordering of memory systems (processor optimizations)

as-if-serial principle: single thread, no matter how to reorder, the execution result of the program is consistent

As in the above example, no matter how the preceding two sentences are sorted, the last sentence sum = a + B is not sorted. This ensures that the results of the program are consistent

Conclusion:

1 reordering does not cause memory visibility issues for single threads

2 multi-threaded multithreaded execution may cause memory visibility issues when re-ordering

Write it here today, and the next one will have the code to demonstrate the theory above.

1 Memory visibility of Java threads

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.