Explore concurrent programming (3) -- Java storage model and shared object

Source: Internet
Author: User

Many programmers do not fully understand the visibility and secure release of a shared variable during initialization (building an object securely and correctly accessing other threads, java is a platform that shields memory details and does not need to be concerned about object recycling. Therefore, most of the visibility and Security releases are published on Alibaba Cloud. In fact, the key lies in the Java storage model, visibility and security release issues are originated from the Java storage structure.

Java Storage Model Principle

Many books and articles have explained the Java storage model, and a figure clearly shows its storage structure:

It can be seen that there is a main memory (main memory or Java heap memory) in the JVM system, all variables in Java are stored in the main memory, and all threads are shared.
Each thread has its own working memory (working memory). The working memory stores copies of some variables in the main memory. The thread operates on all variables in the working memory, threads cannot access each other directly, and variable transmission must be completed through primary storage.

This storage model is similar to our commonly used relationship between cache and database. Therefore, we can infer that the JVM is designed to improve performance, improve the concurrency of multiple threads, and reduce the impact between threads.

Potential problems with the Java Storage Model

1. Cache,
We immediately thought of a cache inconsistency problem, that is, when there is a cache that is inconsistent with the database, we need a mechanism to synchronize data. Similarly, the Java storage model also has this problem. If other threads access a variable initialized by a thread in its working memory before it can be synchronized to the main memory, unexpected problems may occur. In addition, at the underlying design, JVM may execute commands in different operation sequence for variables that are not synchronized to the primary storage. For example:

Public class possiblereordering {<br/> static int x = 0, y = 0; <br/> static int A = 0, B = 0; <br/> Public static void main (string [] ARGs) <br/> throws interruptedexception {<br/> thread one = new thread (New runnable () {<br/> Public void run () {<br/> A = 1; <br/> X = B; <br/>}< br/> }); <br/> thread Other = new thread (New runnable () {<br/> Public void run () {<br/> B = 1; <br/> Y = A; <br/>}< br/>}); <br/> one. start (); Other. start (); <br/> one. join (); Other. join (); <br/> system. out. println ("(" + x + "," + Y + ")"); <br/>}< br/>

Because the variables X, Y, A, and B are not securely released, the four assignment operations may not be performed in the specified operation sequence. The following sequence may appear:

This problem can also be understood, because since these objects are invisible, that is to say, they should be isolated in the work zone of each thread, there are some irrelevant commands, it is also feasible for JVM to disrupt the sequence of execution.

To sum up, there are two potential problems:

  • Cache inconsistency
  • Re-Sort execution

Solve potential problems of the Java Storage Model

In order to allow developers to program securely and correctly on the Java storage model, JVM provides a happens-before principle, which is well organized. I will extract the following:

  • In the program sequence, each operation in the thread occurs before each operation to be executed after the current operation.
  • The object monitor is unlocked before waiting for the thread to get the object lock.
  • The write operation on the variable modified by the volitile keyword occurs before reading the variable.
  • The thread. Start () of a thread is called before all operations in the start thread.
  • All operations in the thread occur before all other threads returned successfully from the thread. Join.

The principles are not enough. Java provides the following tools and methods to ensure variable visibility and secure release:

  • Use
    Synchronized to synchronize variable initialization. This method will immediately synchronize the variables in the working memory to the main memory.
  • Use
    The volatile keyword is used to indicate variables. This method will directly store the variables in the primary memory instead of in the working memory.
  • Final variable. Constants are also stored in primary storage.

In addition, it must be clear that only shared variables will have the above problems. If the variables are only used by this thread, you don't have to worry about so many problems.

After figuring out the Java storage model, it is easier to look at the shared object visibility and security release issues.

Share Object visibility


When an object is synchronized from the working memory to the primary memory, it is invisible. If other threads access invisible objects, the visibility issue may occur. See the following example:

Public class novisibility {<br/> Private Static Boolean ready; <br/> Private Static int number; <br/> Private Static class readerthread extends thread {<br/> Public void run () {<br/> while (! Ready) <br/> thread. yield (); <br/> system. out. println (number); <br/>}< br/> Public static void main (string [] ARGs) {<br/> New readerthread (). start (); <br/> Number = 42; <br/> ready = true; <br/>}< br/>

According to the normal logic, the output should be 42, but the actual result will be very strange and may never be output (because ready is false ), it may output 0 (ready = true is executed first due to the re-sorting problem ). For a more common example, we all like to use pojo with only the set and get methods to design a domain model, as shown below:

@ Notthreadsafe <br/> public class mutableinteger {<br/> private int value; <br/> Public int get () {return value ;} <br/> Public void set (INT value) {This. value = value ;}< br/>}< br/>

However, when multiple threads access an object at the same time, there may be similar visibility issues.

To ensure the visibility of variables, you can use locks,
Synchronized keywords,
Volatile keyword or set it to final directly

Publish shared Variables

The release of shared variables is similar to the release program we often say, that is, to change a variable that is originally internal to a variable that can be accessed externally. The publishing methods are as follows:

  • Store object references to public static Domains
  • Initialize an object that can be accessed externally
  • Store object references in a collection

Secure publishing is similar to ensuring visibility, that is, to synchronize the publishing action and make the published object visible.

Thread Security

In fact, when we close these variables to access this thread, We can fundamentally avoid the above problems. In reality, there are many examples of using thread closures to safely use objects that are not thread-safe, for example:

  • Swing's visual components and Data Model objects are not thread-safe. They are restricted to the swing event distribution thread to achieve thread security.
  • The JDBC connection object does not require thread security, but the JDBC access mode determines that a connection will only be used by one thread at the same time.
  • Threadlocal limits variables to be shared in this thread


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.