Detail Java multi-threaded support memory visibility

Source: Internet
Author: User

I. The visibility of shared variables between threads

Visibility: A thread's modification of shared variable values can 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 of several threads.

Java Memory Model: describes the access rules for various variables (thread-shared variables) in Java programs, and
The JVM stores the variables in memory and reads out the underlying details of the variable from memory.

Java memory Model (JVM):
All of the variables are stored in main memory.
Each thread has its own independent working memory, which holds a copy of the variable used by the thread (a copy of the variable in main memory).

All operations of a thread on a shared variable must be made in its own working memory and cannot be read and written directly from the main memory.
Variables in the working memory of other threads cannot be accessed directly between different threads, and the transfer of variable values between threads needs to be done through main memory.

"Principle of shared variable visibility implementation"
Thread 1 changes to shared variables to be seen by thread 2 in a timely manner, must go through the following 2 steps:
Refreshes the shared variables that were updated in working memory 1 into main memory.
Updates the value of the most recent shared variable in main memory to work memory 2.

Ii. Synchronized realization of visibility

Third, volatile realization of visibility
★ Order Reordering
★as-if-serial semantics
★volatile Precautions for use

Iv. comparison of synchronized and volatile

Detail Java multi-threaded support memory visibility

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.