Java memory model and JVM memory management

Source: Internet
Author: User
Tags volatile

Java memory Model and the JVM Memory Management

One, theJava memory model:

1. main memory and working memory (that is, local memory):

  The main goal of the Java memory model is to define access rules for variables in the program, that is, the underlying details of storing variables in the JVM into memory and removing variables from memory. The variables here differ from the variables in Java programming, which contain instance fields, static fields, and elements that make up the array object, but do not contain local variables and method parameters, because the latter is thread-private and not shared. Of course there is no data competition problem (if the local variable is a reference reference type, the object it refers to can be shared by each thread in the Java heap, but the reference reference itself is thread-private in the local variable table of the Java stack). In order to achieve high performance, the Java memory model does not restrict the execution of specific registers or caches that use the processor to interact with the main memory, nor does it limit the immediate compiler's optimizations to adjust the order of code execution.

JMM Specifies that all variables are stored in the main memory . Each thread also has its own working memory (working memories), and the thread's working memory holds a copy of the main memory of the variable used by the thread, and all the thread-to-variable operations (read, Assignment, etc.) must be done in working memory, not directly read and write to the variables in main memory (the volatile variable still has a copy of the working memory, but because of its special sequence of operations, it looks like read-write access directly in main memory). There is no direct access to variables in the other's working memory between different threads, and the transfer of values between threads needs to be done through main memory.

As a good response to the relationship between main memory and thread working memory (that is, local memory):

When the middle thread A and thread B want to interact with the data, they will experience:

1. thread A Flushes the updated shared variables in local memory B to the main memory.

2. thread B goes to main memory to read the shared variable that thread a refreshed, and then copy a copy to local memory B .

2. three major features: atomicity, visibility and ordering

The Java memory model is built around these three features in concurrent programming.

Atomic Nature (atomicity):

An operation cannot be interrupted, either fully executed, or not executed. This is somewhat similar to a transactional operation, where all execution succeeds or is rolled back to the state before the operation was performed. Access to basic type data is mostly atomic operations.

Visibility of:

Once a thread has modified the shared variable, the other thread can immediately see (perceive) the variable (change).

The Java memory model implements visibility by synchronizing the modified values of variables in working memory to main memory, refreshing the latest values from the main memory to the working memory before reading the variables, and relying on the main memory.

Order:

for the code of a thread, we always assume that the code is executed from the point of the go, and then in turn. This cannot be said completely wrong, in a single-threaded program, it is true, but in multi-threaded concurrency, the execution of programs may appear disorderly order. One sentence can be summed up as: In this thread to observe, the operation is orderly; If you look at another thread in a thread, all operations are unordered. The first half of the sentence refers to "line range is expressed as serial semantics (within thread as-if-serial semantics)", the latter sentence refers to "instruction rearrangement" phenomenon and "working memory and main memory synchronization delay" phenomenon.

Java provides two keyword volatile and synchronized to ensure the order of operations between multithreading, the volatile keyword itself by adding a memory barrier to prohibit the reordering of instructions, The Synchronized keyword is implemented by a variable that allows only one thread to lock it at the same time.

In a single-threaded program, there is no "command reflow" and "Working memory and Master Memory Synchronization Latency" phenomena, only in multithreaded programs.

3,happens-before principle:

The order relationship between the two operations defined in the Java memory model, if operation a precedes action B, the effect of operation A can be observed by Action B, which includes modifying the values of shared variables in memory, sending messages, calling methods, and so on.

If the relationship between the two operations is not there and cannot be deduced from the following rules, they are not guaranteed to be sequential, and the virtual machine can reorder them arbitrarily.

L Sequence rules (pragram order rule): In a thread, according to the Order of the program code, the preceding operation occurs in the previous operation. It should be accurate to control the flow order rather than the program code order, because the branching and looping structures are considered.

L Tube Lock rule : A unlock operation first occurs after the lock operation facing the same lock. The same lock must be emphasized here, and the "back" refers to the chronological order of the time.

L volatile variable rules (volatile Variable rule): Write to a volatile variable precedes the read operation of the variable, where the "back" also refers to the chronological order.

L d. Thread start rule: the Start () method of the thread object takes precedence over each action of this thread.

L thread finally rule (thread termination rule): All operations in the thread occur first in the termination detection of this thread, we can end with the Thread.Join () method, Thread.isalive () The return value of such a segment detects that the thread has terminated execution.

L thread Break rule interruption: The call to the thread interrupt () method occurs when the code of the interrupted thread detects that the interrupt event occurred, and can be passed thread.interrupted () method to detect if an interrupt occurred.

L object Finalization rule (Finalizer rule): An object initialization completion (construction method execution completion) occurs first at the beginning of its finalize () method.

L transitivity (transitivity): If the operation a first occurs in operation B, Operation B first occurs in Operation C, it can be concluded that operation a precedes operation C.

an operation "time first" does not mean that the operation will be "antecedent", then if an operation "first occurrence" whether it can be deduced that the operation must be "time to occur"? is also not tenable, a typical example is the order reordering. So the order of time and the Happens-before principle has nothing to do with the basic, so the measurement of concurrency security issues must be based on the Happens-before principle.

Second, JVM Memory Management

During the execution of a Java program, the JVM divides the memory it manages into several different data regions, each of which has its own purpose, creation time, and destruction time.

The Java runtime data is differentiated into the following memory areas: (as shown)

1.PC Register/Program counter:

is strictly a data structure that holds the memory address of the currently executing program, as Java is a multi-threaded execution, so the trajectory of the program execution is not always linear execution. When multiple threads cross execution, the program of the interrupted thread is currently executing to which memory address must be saved so that the thread being used for the interruption resumes execution and then continues execution at the instruction address when it was interrupted. In order to return to the correct execution location after thread switching, each thread needs to have a separate program counter, the counters between the various threads do not affect each other, isolated storage, we call this kind of memory area as "thread-private" memory, which is somewhat similar to "ThreadLocal", is thread-safe.

2.Java Stack Java stack:

  The Java stack is always associated with threads, and whenever a thread is created, the JVM creates the corresponding Java stack for that thread, which in turn contains multiple stack frames (stack frame) that are associated with each method, creating a stack frame each time a method is run. Each stack frame contains information such as local variables, operation Stacks, and method return values. Whenever a method executes, the stack frame pops up the element of the stack frame as the return value of the method, and the stack frame at the top of the Java stack is the stack frame that is currently executing, i.e. the current executing method, and the PC register points to that address. Only the local variables of this active stack frame can be used by the manipulation stack, and when another method is called in this stack frame, a new stack frame corresponding to it is created, and the newly created stack frame is placed on top of the Java stack and becomes the current active stack. Also now only the local variables of this stack can be used, when all the instructions in this stack frame are completed, the stack frame is removed from the Java stack, the stack frame just now becomes the active stack frame, the return value of the front stack frame becomes an operand of this stack frame's Operation Stack.

because Java stacks are related to threads, and Java stack data is not shared by threads, so there is no need to be concerned about their data consistency or the problem of synchronous locks.

in the In the Java Virtual Machine specification, there are two exceptions to this area: if the thread requests a stack depth greater than the virtual machine allows, the STACKOVERFLOWERROR exception will be thrown, and if the virtual machine can be dynamically extended, if the extension cannot request enough memory, The OutOfMemoryError exception is thrown. In a hot spot virtual machine, you can use the-XSS parameter to set the size of the stack. The size of the stack directly determines the reach depth of the function call.

3 Heap:

Heap is Memory managed by the JVM the largest chunk in China is shared by all Java thread locks, not thread-safe, created when the JVM is started. The heap is where Java objects are stored, as described in the Java Virtual Machine specification: All object instances and arrays are allocated on the heap. Java heap is the main area of GC management, from the perspective of memory recycling, since the GC basically uses the Generational collection algorithm, so the Java heap can be subdivided into: the new generation and the old age; the new generation is more detailed with Eden Space, from Survivor space, to Survivor space and so on.

4. Method Area:

The method area holds information about the class to be loaded (name, modifier, and so on), static constants in the class, constants defined in the class as final, field information in the class, method information in the class, This data is derived from the method area when the information is obtained by means of the class object's Getname.isinterface in the program. The method area is shared by the Java thread lock, unlike the rest of the Java heap, which is frequently recycled by GC, it stores information that is relatively stable, is GC-OutOfMemory when the method area is using more memory than it allows, and throws an error message. The method area is also part of the heap, which is what we typically call the persistent zone permanet Generation in the Java heap, which can be set by parameters and can be specified by-xx:permsize,-xx:maxpermsize specifying the maximum value.

5. Constant pool constant pool:

The constant pool itself is a data structure in the method area. Constant pools are stored in constants such as strings,final variable values, class names, and method names. The Chang is determined during compilation and is saved in the compiled. class file. Generally divided into two categories: literal and application volume. Literals are strings, final variables, and so on. The class name and method name belong to the reference amount. The most common reference amount is when invoking a method, a reference to the method is found based on the method name, and the function code is executed in the body. The reference amount consists of the name of the class and interface, the name and descriptor of the field, and the names and descriptors of the method.

6. Local methods Stack native method stack:

local method Stacks and The Java stack plays a very similar role, except that the Java stack executes Java method Services for the JVM, while the local method stack executes the native method service for the JVM. The local method stack also throws Stackoverflowerror and OutOfMemoryError exceptions.

Java memory model and JVM memory management

Related Article

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.