Memory Management _java Memory management

Source: Internet
Author: User

The Java Virtual Machine specification attempts to define a Java memory model (MODEL,JMM) that masks memory access differences between the various hardware platforms and operating systems to enable Java programs to achieve consistent memory access across various platforms. So what does the Java memory model prescribe, which defines the access rules for variables in the program, and, to a large extent, defines the order in which the program executes. Note that for better execution performance, the Java memory model does not restrict the execution engine from using the processor's registers or caches to increase instruction execution speed, nor does it restrict the compiler from reordering instructions. In other words, in the Java memory model, there is also the problem of cache consistency and instruction reordering.

  The Java memory model stipulates that all variables are present in main memory (similar to the physical memory mentioned earlier), and each thread has its own working memory ( similar to the previous cache). all the operations of a thread on a variable must be done in working memory, not directly on main storage. And each thread cannot access the working memory of other threads.

1. atomicity

In Java, read and assign operations to variables of the base data type are atomic operations, meaning that these operations are not interrupted, executed, or not executed.

The above sentence, though seemingly simple, is not so easy to understand. Take a look at the following example I:

Please analyze which of the following actions are atomic operations:

x = ten;         Statement 1y = x;         Statement 2x++;           Statement 3x = x + 1;     Statement 4

at first glance, some friends may say that the actions in the 4 statements above are atomic operations. In fact, only statement 1 is an atomic operation, and the other three statements are not atomic in nature.

Statement 1 is to assign a value of 10 directly to X, which means that the thread executes the statement and writes the value 10 directly to the working memory.

Statement 2 actually contains 2 operations, it first to read the value of x, and then write the value of x to the working memory, although reading the value of x and the value of x to the working memory of the 2 operations are atomic operations, but together is not atomic operation.

Similarly, X + + and × = x+1 include 3 operations: reads the value of x, adds 1 operations, and writes a new value.

So the above 4 statements only have the atomicity of statement 1 operations.

That is, only a simple read, assignment (and must assign a number to a variable, the reciprocal assignment of a variable is not an atomic operation) is the atomic Operation .

But here's one thing to note: Under 32-bit platforms, the reading and assignment of 64-bit data is done by two operations and cannot be guaranteed to be atomic. But it seems that in the latest JDK, the JVM has guaranteed that reading and assigning 64 bits of data is also atomic.

As can be seen from the above, theJava memory model only guarantees that basic reading and assignment are atomic operations , and if you want to achieve the atomicity of a wider range of operations, you can do so by synchronized and lock. Since synchronized and lock can guarantee that only one thread executes the block at any one time, there is no atomic problem, which guarantees atomicity.

2. Visibility

For visibility, Java provides the volatile keyword to guarantee visibility.

When a shared variable is modified by volatile, it guarantees that the modified value is immediately updated to main memory, and when other threads need to read it, it will read the new value in RAM.

The common shared variable does not guarantee visibility, because when a common shared variable is modified, it is indeterminate when it is written to main memory, and when other threads go to read it may be the original old value at this time and therefore cannot guarantee visibility.

In addition, visibility is ensured through synchronized and lock, and synchronized and lock ensure that only one thread acquires the lock at the same time and executes the synchronization code, and that changes to the variable are flushed to main memory before the lock is released. Visibility can therefore be guaranteed.

3. Order

In the Java memory model, the compiler and processor are allowed to reorder instructions, but the reordering process does not affect the execution of a single-threaded procedure, but it can affect the correctness of multithreaded concurrency execution.

In Java, you can use the volatile keyword to ensure a certain "order" (the specific principle is described in the next section). It is also possible to maintain order through synchronized and lock, and it is clear that synchronized and lock ensure that each time a thread executes the synchronous code, which is the equivalent of allowing the thread to execute the synchronization code in order, naturally guaranteeing order.

In addition, theJava memory model has some innate "order", that is, no need to be guaranteed by any means of order, which is often referred to as the Happens-before principle. If the order of execution of two operations cannot be deduced from the happens-before principle, then they cannot guarantee their order, and the virtual machine can reorder them arbitrarily.

The following is a detailed introduction to the following Happens-before principles (the first occurrence principle):

    • Program Order rules: Within a thread, in code order, the preceding operation precedes the operation that is written in the back
    • Locking rule: A unlock operation occurs after the face of the same lock amount lock operation
    • Volatile variable rule: The write operation of a variable precedes the read operation that faces the variable.
    • Delivery rule: If operation a precedes operation B, and Operation B precedes Operation C, it can be concluded that operation a precedes operation C
    • Thread Start rule: the Start () method of the thread object takes precedence over each action of this thread
    • Thread Break rule: The call to the thread interrupt () method occurs when the code of the interrupted thread detects that the interrupt event occurred
    • Thread termination rule: All operations in a thread occur first in thread termination detection, and we can detect that the thread has terminated execution by means of the Thread.Join () method end, Thread.isalive () return value
    • Object Finalization rule: Initialization of an object occurs at the beginning of his finalize () method

These 8 principles are excerpted from the in-depth understanding of Java virtual machines.

Of these 8 rules, the first 4 rules are more important, and the last 4 rules are obvious.

Let's explain the first 4 rules:

For procedural order rules, my understanding is that the execution of a program code looks orderly in a single thread. Note that although this rule mentions "writing in front of operations that occur in the following operations", this should be the order in which the program appears to execute in code order, because the virtual machine may order the program code to reorder. Although it is reordered, the result of the final execution is consistent with the results of the program's sequential execution, which only re-sorts instructions that do not have data dependencies. Therefore, it is important to understand that in a single thread, program execution appears to be executed in an orderly manner. In fact, this rule is used to ensure that the program executes the results in a single thread, but there is no guarantee that the program will perform correctly in multiple threads.

The second rule is also easier to understand, that is, in a single thread or multi-threading, if the same lock is in a locked state, then the lock must be released before continuing the lock operation.

The third rule is a more important rule, and it is the content that will be emphasized in the following article. The intuitive explanation is that if a thread goes first to write a variable and then a thread goes to read it, the write operation will definitely take place in the read operation.

The fourth rule is actually embodies the happens-before principle has the transitive nature.

Memory Management _java Memory management

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.