Java Learning: The JVM memory model

Source: Internet
Author: User
Tags xms

First, the article for the reason

Started the internship, the internship to the Java Development Engineer ...

Second, the JVM memory model general diagram

In Java, multiple tasks are processed at the same time through multithreading, and all threads share the JVM memory area, and each thread has its own working memory, and when the thread interacts with the memory area, the data is copied from the main storage to the working memory, which is then processed by the thread (opcode + operand).

As we have mentioned before, the logical memory model of the JVM is as follows:

Third, JVM memory model detailed 1, program counter

Program Counter Register is a small amount of memory space, its role can be seen

is the line number indicator of the bytecode that is being executed by the current thread. In the conceptual model of the virtual machine (only the conceptual model,

Various virtual machines may be implemented in more efficient ways, and the bytecode interpreter works by changing

The value of this counter selects the next byte-code instruction to be executed, branching, looping, jumping, exception handling,

Basic functions such as thread recovery need to rely on this counter to complete.

Because the multithreading of a Java Virtual machine is achieved by changing threads in turn and allocating processor execution time

, at any given moment, a processor (a kernel for a multicore processor) executes only

The instructions in a thread. Therefore, in order for the thread to switch back to the correct execution location, each thread needs

there is a separate program counter , the counters between the threads do not affect each other, independent storage, we call this type of internal

The storage area is "thread-private" memory.

If the thread is executing a Java method, this counter logs the virtual machine bytes that are being executed

If the Natvie method is being executed, the counter value is empty (Undefined). This

The memory area is the only area in the Java Virtual Machine specification that does not stipulate any outofmemoryerror conditions.

2. Java Virtual Machine stack

Like program counters, theJava Virtual machine stack (Java Stacks) is also thread-private ,

It has the same life cycle as the thread. The stack mainly contains some basic types of variables (, int, short, long, byte, float,

A double, Boolean, char), and an object handle. Stack has a very important particularity, is that there is data in the stack can be shared.

Java memory is often divided into heap memory (heap) and stack memory (stack), which is more coarse

The division of Java memory areas is actually far more complex than this. The popularity of this partitioning method can only be explained by most programs

The memory area most closely related to the object memory allocation is the two blocks. Refers to the "stack" is now talking about the virtual machine

Stack, or a local variable table part of the virtual machine stack.

The local variable table holds the various basic data types that are known at compile time (Boolean, Byte, char, short, int,

Float, long, double), object reference (reference type, which is not equivalent to the object itself, according to the different virtual

A reference pointer to the start address of an object, or to a handle that represents an object or

Other locations associated with this object) and the ReturnAddress type (which points to the address of a bytecode directive).

Where 64-bit long and double types of data consume 2 local variable space (slots), the rest

Data type only takes up to 1. The memory space required for the local variable table is allocated during compilation, when entering a

method, this method needs to allocate how much local variable space in the frame is fully deterministic, during the method run

Does not change the size of the local variable table.

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 stack can be dynamically extended (most of the current Java virtual machines can be dynamically extended, However, a fixed-length virtual machine stack is also allowed in the Java Virtual Machine specification, which throws a OutOfMemoryError exception when the extension fails to request enough memory.

3. Local Method Stack

The local methods Stack (Native method Stacks) is very similar to the virtual machine stack, and its

The difference is that the virtual machine stack executes Java methods (that is, bytecode) services for the virtual machine, while the local method stack

is the native method service that is used for the virtual machine. The language used in the virtual machine specification for methods in the local method stack

Usage and data structures are not mandatory, so specific virtual machines can be implemented freely. Even

Some virtual machines, such as sun HotSpot virtual machines, directly combine the local method stack with the virtual machine stack.

As with the virtual machine stack, the local method stack area throws Stackoverflowerror and OutOfMemoryError

Abnormal.

4. Java Heap

For most applications, the Java heap (Java heap) is the largest in-memory managed by a Java virtual machine.

A. The Java heap is a piece of memory that is shared by all threads and created when the virtual machine is started. of this memory area

The only purpose is to store object instances where almost all of the object instances are allocated memory . This is true in Java virtual

The description in the quasi-machine specification is that all object instances and arrays are allocated ① on the heap, but with the JIT compiler

Development and the gradual maturation of escape analysis technology, stack allocation, scalar replacement ② optimization technology will lead to some subtle

Changes occur, all objects are allocated on the heap and gradually become less "absolute".

The Java heap is the main area of garbage collector management, so it is often called a "GC heap" (Garbage

Collected heap, fortunately domestic not translated into "rubbish heap"). If from the perspective of memory recycling, because now

Collectors are basically the use of generational collection algorithm, so the Java heap can also be subdivided into: the new generation and the old age;

A little more detailed is Eden space, from Survivor space, to Survivor space and so on. If you allocate from memory

View, the thread-shared Java heap may divide multiple thread-private allocation buffers (thread Local

Allocation Buffer,tlab). However, regardless of the partition, it is not related to the contents, no matter what area,

The storage is still an object instance and is further divided to better reclaim memory, or to allocate it more quickly

Memory. In this chapter, we only discuss the role of memory areas, and the various areas of the Java heap

Details such as allocation and recycling will be the subject of the next chapter.

According to the Java Virtual Machine specification, the Java heap can be in a physically discontinuous memory space, as long as

It's logically contiguous, just like our disk space. When implemented, it can be implemented as a fixed size

can also be extensible, but the current mainstream virtual machines are implemented in a scalable way (via-XMX

and-xms control). If there is no memory in the heap to complete the instance assignment, and the heap cannot be expanded, it will throw

OutOfMemoryError exception.

4. Method area

The method area, like the Java heap, is an area of memory shared by each thread that is used to store

Data such as class information, constants, static variables, instant compiler compiled code, and so on, that have been loaded by the virtual machine. Although

The Java Virtual machine specification describes the method area as a logical part of the heap, but it has an alias called non-

Heap (not heaps), which should be distinguished from the Java heap.

For developers who are accustomed to developing and deploying programs on a hotspot virtual machine, many people are willing to take the method area

Called "Permanent Generation" (Permanent Generation), is essentially not equivalent, just because the hotspot virtual

The design team of the machine chooses to extend the GC collection to the method area, or use the permanent generation to implement the method area

Has. For other virtual machines (such as Bea JRockit, IBM J9, etc.) there is no concept of a permanent generation. That

Make it the hotspot virtual machine itself, according to the official roadmap information, now also has to abandon the permanent generation and "move"

To native Memory to achieve the planning of the method area.

The Java Virtual Machine specification has a very loose limit on this area, except that the Java heap does not require continuous internal

Storage and can choose a fixed size or extensible, you can also choose not to implement garbage collection. Comparatively speaking, rubbish

The collection behavior is less present in this area, but the data is not entered into the method area as the name of the permanent Generation One

The "permanent" existence of the sample. The memory recovery target for this area is primarily for the recovery of constant pools and the unloading of types

In general, the recovery "score" in this area is more difficult to satisfy, especially the type of unloading, conditions

Very harsh, but the recovery of this part of the area is indeed necessary. In the Sun company Bug list,

Several serious bugs are due to the fact that a low-release hotspot virtual machine is not fully recyclable for this area.

A memory leak is caused.

According to the Java Virtual Machine specification, when the method area does not meet the memory allocation requirements, it throws

OutOfMemoryError exception.

5. Running a constant-rate pool

The runtime Constant pool is part of the method area. In addition to the Class file, there is

Information such as the version, field, method, interface, and so on, there is also a constant pool (Constant

Table), which holds the various literal and symbolic references generated during the compilation period, which will be stored after the class is loaded

To the run-time-constant pool of the method area.

Java virtual machines have strict rules for every part of a class file (naturally also including Chang)

Each byte to store which data must conform to the requirements of the specification, so that it will be recognized by the virtual machine,

Load and execute. But for running a constant pool, the Java virtual machine specification does not require any detail, and different

A virtual machine implemented by a provider can implement this memory area as needed. However, in general, in addition to

To save the symbolic references described in the class file, and also store the translated direct references in the run-time

① in the volume pool.

Another important feature of running a constant pool with respect to the regular pool of class files is the dynamic nature of the Java language

Words do not require constants to be generated only at compile time, that is, the contents of a constant pool that is not pre-built into a class file

To enter the method area to run the constant pool, and the new constants may be put into the pool during the run, this feature is developed

The Intern () method of the string class is used by more people.

Since the run-time constant pool is part of the method area, it is naturally limited by the method area memory, when the constant pool is not

The OutOfMemoryError exception is thrown when the method is re-applied to memory

6. Direct Memory

Direct memory is not part of the data area when the virtual runtime is running, nor is it Java

The memory area defined in the virtual machine specification, but this part of the memory is also used frequently, and may also lead to

OutOfMemoryError abnormal appearance, so we put it here to explain together.

The new Input/output class was added to JDK 1.4, introducing a channel-based

With buffer, it can use the native function library to directly allocate out-of-heap memory,

After a Directbytebuffer object stored in the Java heap as a reference to this memory

Operation. This can significantly improve performance in some scenarios because it avoids the Java heap and the native heap

Copy the data back.

Obviously, the allocation of native direct memory is not limited by the Java heap size, but, since it is memory,

Must still be the size and processor of the total memory of the machine (including RAM and swap or paging files)

The limit for addressing space. When the server administrator configures the virtual machine parameters, it is generally based on the actual memory settings-xmx

parameter information, but often ignores direct memory, so that the sum of each memory area is greater than the physical memory limit

(including physical and operating system-level limitations), resulting in dynamic scaling when outofmemoryerror occurs

Abnormal.

Logical memory model we've seen that, so how do we access it when we build an object?

In the Java language, how is Object access performed? Object access is ubiquitous in the Java language and is the most common program behavior, but even the simplest accesses involve the three most important memory areas of the Java stack, the Java heap, and the method area

The association between domains, as in the following code:

Object obj = new Object ();

Assuming that this code appears in the method body, the semantics of this part of "Object obj" will be reflected in the Java stack

The local variable table, as a reference type data appears. And the semantics of the section "New Object ()"

will be reflected in the Java heap, forming a piece that stores all instance data values for object type Instance data,

Data from each instance field in the image), and the object memory fabric implemented by the virtual machine

(Object memory Layout), the length of this piece of memory is not fixed. In addition, in the Java heap

You must also include a place where you can find data for this object type, such as Object type, parent class, implemented interfaces, methods, and so on.

Data is stored in the method area.

Because the reference type only specifies a reference to the object in the Java Virtual Machine specification, there is no

Defines the way in which this reference should be located, and access to the exact location of objects in the Java heap, so

Access to objects varies from one virtual machine to another, and there are two main ways to access them: using Handles and direct

Pointer.

If you use handle access, a chunk of memory will be partitioned into the Java heap as a handle pool, reference

is the handle address of the object, and the handle contains the object instance data and the type data

The specific address information, as shown in.

If you use the direct pointer access method,

The layout of the Java heap object must consider how to place the access type

Information about the data, the object address is stored directly in the reference, as shown in

There are advantages to how both of these objects are accessed, and the greatest benefit of using handle access is

Reference in storage
Stored is a stable handle address, when the object is moved (garbage collection is a very common behavior when moving objects) only

The instance data pointer in the handle is changed, and the reference itself does not need to be modified.

The biggest benefit of using direct pointer access is faster speed, which saves time for pointer positioning

Because object access is very frequent in Java, such overhead is a very significant

Execution costs. For the main virtual machine discussed in this book, Sun HotSpot, which uses the second approach to object access, is very common in the context of the overall software development, where the various languages and frameworks are accessed using handles.

Iv. JVM Memory Model Example 1, Java heap Overflow

In the following process we limit the size of the Java heap to 20MB, not extensible (-xms the minimum value of the heap to the parameter

The-XMX parameter is set to the same as the maximum value to avoid auto-scaling of the heap), by the parameter-xx:+heapdump

Onoutofmemoryerror allows the virtual machine to dump the current memory heap dump when a memory overflow exception occurs

Snapshots for post-mortem analysis.

The parameters are set as follows

 PackageCom.yhj.jvm.memory.heap;ImportJava.util.ArrayList;ImportJava.util.List;/** * @Described: Heap Overflow test * @VM args:-verbose:gc-xms20m-xmx20m-xx:+printgcdetails * @FileNmae /c6> Com.yhj.jvm.memory.heap.HeapOutOfMemory.java * / Public  class heapoutofmemory {    /** * @param args * @Author yhj Create at 2011-11-12 pm 07:52:18 * *     Public Static void Main(string[] args) {List<testcase> cases =NewArraylist<testcase> (); while(true) {Cases.add (NewTestCase ()); }    }}/** * @Described: Test case * @FileNmae Com.yhj.jvm.memory.heap.HeapOutOfMemory.java */Class testcase{}

The outofmemoryerror exception for Java heap memory is the most common memory overflow exception in practical applications. Appears in the Java heap
The exception stack information "Java.lang.OutOfMemoryError" is followed by a further hint "Java heap

Space ".

To solve the anomaly in this area, the general approach is to first pass the Memory image analysis tool (such as Eclipse

Memory Analyzer) analyzes the dump heap dump snapshot, focusing on confirming that the objects in

It is necessary to first understand whether there is a memory leak or memory Leak

Out (Memory Overflow). Figure 2-5 shows the heap dumps opened with Eclipse Memory Analyzer.

According to the document.

In the case of a memory leak, further tools can be used to view the reference chain of the leaking object to the GC Roots. So it

Can find out what path the leak is associated with GC Roots and causes the garbage collector to not be automatically recycled

of them. Having mastered the type information of the leaking object and the information of the GC Roots reference chain, it can be more accurate

Position the leak code.

If there are no leaks, in other words, the objects in memory must still exist, then you should check

Virtual machine heap parameters (-XMX and-XMS), compared to the physical memory of the machine to see if you can also adjust the size, from the code

Attempts to reduce program run time by checking for the presence of certain objects that have a long life cycle and too long hold status

Memory consumption.

2. Java Stack Overflow
 PackageCom.yhj.jvm.memory.stack;/** * @Described: Insufficient stack level exploration * @VM args:-xss128k * @FileNmae Com.yhj.jvm.memory.stack.StackOverFlow.java * * Public  class stackoverflow {    Private intI Public void Plus() {i++;    Plus (); }/** * @param args * */     Public Static void Main(string[] args) {StackOverflow StackOverflow =NewStackOverflow ();Try{Stackoverflow.plus (); }Catch(Exception e) {System.out.println ("Exception:stack Length:"+STACKOVERFLOW.I);       E.printstacktrace (); }Catch(Error e) {System.out.println ("Error:stack Length:"+STACKOVERFLOW.I);       E.printstacktrace (); }    }}
3, Chang overflow
 PackageCom.yhj.jvm.memory.constant;ImportJava.util.ArrayList;ImportJava.util.List;/** * @Described: Constant pool memory Overflow Explore * @VM args:-xx:permsize=10m-xx:maxpermsize=10m * @FileNmae C Om.yhj.jvm.memory.constant.ConstantOutOfMemory.java * * Public  class constantoutofmemory {    /** * @param args * @throws Exception */     Public Static void Main(string[] args)throwsException {Try{List<string> strings =NewArraylist<string> ();inti =0; while(true) {Strings.add (string.valueof (i++). Intern ()); }       }Catch(Exception e) {E.printstacktrace ();ThrowE }    }}
4. Method Area Overflow
 PackageCom.yhj.jvm.memory.methodArea;ImportJava.lang.reflect.Method;ImportNet.sf.cglib.proxy.Enhancer;ImportNet.sf.cglib.proxy.MethodInterceptor;ImportNet.sf.cglib.proxy.MethodProxy;/** * @Described: Method Area Overflow Test * using technology Cblib * @VM args:-xx:permsize=10m-xx:maxpermsize=10m * @FileN Mae Com.yhj.jvm.memory.methodArea.MethodAreaOutOfMemory.java * / Public  class methodareaoutofmemory {    /** * @param args * *     Public Static void Main(string[] args) { while(true) {Enhancer enhancer =NewEnhancer ();           Enhancer.setsuperclass (Testcase.class); Enhancer.setusecache (false); Enhancer.setcallback (NewMethodinterceptor () {@Override               PublicObjectIntercept(Object arg0, Method arg1, object[] arg2, Methodproxy arg3)throwsThrowable {returnArg3.invokesuper (arg0, arg2);           }           });       Enhancer.create (); }    }}/** * @Described: Test case * @FileNmae Com.yhj.jvm.memory.methodArea.MethodAreaOutOfMemory.java */ Class testcase{}
5. Direct Memory Overflow
 PackageCom.yhj.jvm.memory.directoryMemory;ImportJava.lang.reflect.Field;ImportSun.misc.Unsafe;/** * @Described: Direct Memory Overflow test * @VM args:-xmx20m-xx:maxdirectmemorysize=10m * @FileNmae Com.yhj.jvm.memory.directoryMemory.DirectoryMemoryOutOfmemory.java * * Public  class directorymemoryoutofmemory {    Private Static Final intONE_MB =1024x768*1024x768;Private Static intCount =1;/** * @param args * *     Public Static void Main(string[] args) {Try{Field field = Unsafe.class.getDeclaredField ("Theunsafe"); Field.setaccessible (true); unsafe unsafe = (unsafe) field.get (NULL); while(true) {unsafe.allocatememory (ONE_MB);           count++; }       }Catch(Exception e) {System.out.println ("Exception:instance created"+count);       E.printstacktrace (); }Catch(Error e) {System.out.println ("Error:instance created"+count);       E.printstacktrace (); }    }}
Resources

[1] http://www.cnblogs.com/dingyingsi/p/3760447.html

Java Learning: The JVM memory model

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.