N high-frequency interview questions about the JVM memory!

Article from: melonstreet

table of Contents

  • JVM memory area is how divided?

  • OOM which may occur in the area?

  • Heap memory structure?

  • Common performance monitoring and fault location tools What?

  • reference


JVM memory area is how divided?

JVM memory division, some areas are private to the thread, some belong to the entire JVM process, some regions will throw an exception OOM, some will not.

Learn JVM memory zoning and features of the line memory is the basis for the positioning problem.

The JVM memory area is how divided it?

First, the program counter (Program Counter Register), the JVM specification, each thread has its own program counter.

This is a relatively small memory space, JVM Java instruction address storage method currently executing thread, ie bytecode line number. If you are performing Native method, this counter is empty.

In addition, the memory region is the only one in the Java virtual machine specification does not provide any OOM area of memory situation.

Second, the Java virtual machine stack (Java Virtal Machine Stack), is also part of the thread private area.

Each thread will be created in the creation of a virtual machine stack, consistent with the life cycle of a thread, a thread exits, the thread stack also recovered virtual machines.

Internal virtual machine stack to keep one stack frame, each method call will be push, JVM operations on the stack frame of the stack and push only two kinds of pop operations will be carried out at the end of the method call.

The local variable table area stores, various known basic compile time type data, object reference information for export and the like.

Third, native method stacks (Native Method Stack) with the virtual machine stack similar to the native method stack is a stack used when calling a local method, each thread has a native method stacks.

Fourth, the heap (Heap), Java object instance almost all creation, are to be allocated directly to the heap.

Stack is shared by all threads in the area of ​​the heap, it will be further divided garbage collector, such as division of the new generation, old age.

Java virtual machine at boot time, you can use the parameter "Xmx" like the size of the heap designated area.

Fifth, the method area (Method Area). The method area and the heap, just as all the threads share, store the virtual machine is loaded yuan (Meta) data, including class information, constants, static variables, the time compiler to compile the code and other data.

It should be noted that the runtime constant pool area is also a method. Under the Java Virtual Machine specification, when the method of memory allocation area can not meet demand, it will throw OutOfMemoryError exception.

Since the early realization of the HotSpot JVM, CG generational collection will expand to the method area, so many people will be the method area called permanent generations.

Oracle JDK8 generations have been permanently removed permanently generations, while increasing the metadata area (Metaspace).

Sixth, the runtime constant pool (Run-Time Constant Pool), which is part of the district method, the method is limited by the memory area, when the constant pool can no longer apply to memory, it will throw OutOfMemoryError exception.

Class file in addition to the versions of the class, method, fields, and interface description information, as well as a constant pool information.

Class first four bytes of each file is called Magic Number, its purpose is to determine whether it is a virtual machine can be accepted file; the next four bytes are stored in the file version number of Class. Immediately after the version number is constant pool the entrance.

The main constant pool constants stored into two categories:

  • Literal (Literal), such as text strings, final constant value

  • Symbolic references, storage of some constants related to the compilation, because unlike C ++ Java process as there are connected, so a field of these symbolic references will need to be converted at runtime, in order to get the real memory address entry.

class file constant pool, also known as static constant pool , the JVM class virtual machine after the completion of the loading operation, static constant pool will be loaded into memory, stored in the runtime constant pool.

Seventh, the direct memory (Direct Memory), direct memory is not part of belonging to the Java virtual machine operating data area specified in the Java specification.

The NIO Java Native methods may be used directly in the heap memory allocated outer java, using the outer DirectByteBuffer object as referenced heap memory.

This chart below reflects the Java process memory usage running:


OOM which may occur in the area?

According to the description of javadoc, OOM refers to the JVM memory is not enough, and at the same time garbage collector can not provide more memory. As can be seen from the description, before the JVM throws OutOfMemoryError, the garbage collector will generally go into action to try to reclaim memory.

From the above analysis of Java data area, in addition to the program counter OOM does not happen, the situation OOM which areas will happen?

First, the heap memory . Out of heap memory is one of the most common causes of sending OOM

If you do not allocate memory to complete object instances in the heap, and the heap can not be extended again, it will throw an OutOfMemoryError error message is thrown "java.lang.OutOfMemoryError: Java heap space".

The current mainstream JVM can be controlled by -Xmx and -Xms size of heap memory, OOM occurred heap may be a memory leak, it may be unreasonable heap size distribution.

Second, Java virtual machine stack and native method stacks , the difference between these two regions, but the virtual machine execution stack for the Java virtual machine service method, and native method stacks, the virtual machine to use a method of Native service in memory allocation abnormal on the same.

In the JVM specification, the Java Virtual Machine stack provides two anomalies:

  1. If the thread stack size is larger than the requested stack allocated, then throw StackOverFlowError error, such as carried out a recursive call will not stop;

  2. If the virtual machine can dynamically expand the stack is not enough memory to apply when the expansion is thrown an OutOfMemoryError.

Third, direct memory . Although not part of the direct memory virtual machine runtime data area, but since it is memory, physical memory will be limited.

Introduced in JDK1.4 NIO libraries using Native allocate memory directly on the memory heap outside, but directly out of memory, can lead to OOM.

Fourth, the method area . With the introduction of Metaspace metadata area, OOM error method area has become a " java.lang.OutOfMemoryError: Metaspace ."

For older versions of Oracle JDK, due to the limited size of the permanent generation, and garbage collection JVM permanent generation is not positive, if data is written to the continued generation of permanent, such as calling String.Intern (), and take up too much in perpetual generations resulting in insufficient memory space, the problem will appear OOM

Error message corresponding to " java.lang.OutOfMemoryError: PermGen Space "

Memory area Whether private thread Whether OOM can happen
Program Counter Yes no
VM stack Yes Yes
Native method stacks Yes Yes
Methods district no Yes
Direct Memory no Yes
stack no Yes


Heap memory structure?

You can use some tools to understand the contents of memory the JVM, specific to a particular area of ​​memory, what tools should be used to locate it?

  • Graphical tools. Advantage of intuitive graphical tool, when connected to a Java process, heap memory can be displayed, an outer heap memory usage, similar tools have the JConsole , VisualVM like.

  • Command-line tool. Such tools can be queried at runtime, including jstat , jmap , etc., can be viewed on the heap, the method area. Many will also use these tools when positioning line problem. jmap may be green heap dump file ( Heap the Dump ) file, if it is in the linux, heap dump file can be locally pulled using Eclipse MAT analysis, it may also be used jhap analysis.

About memory monitoring and diagnostics, in the back will conduct in-depth understanding. Now look at the next question: structure within the heap is how it?

Standing garbage collector's point of view, the memory can be divided into the old and the new generation's.

Memory allocation rule depends on the current use of a combination of what the garbage collector, and the associated memory configuration parameters.

To the general direction that the object is assigned a priority in the new generation of the Eden area, and large objects directly into the old era.

First, the new generation area of Eden.

Objects priority allocation in the region, while the JVM can allocate a private area of the cache for each thread, called TLAB (the Thread Local Allocation Buffer), avoiding the need to use locking mechanisms to allocate memory when multiple threads simultaneously affect the allocation rate. TLAB allocated on the heap, located in Eden in.

TLAB following structure:

// ThreadLocalAllocBuffer: a descriptor for thread-local storage used by
// the threads for allocation.
//            It is thread-private at any time, but maybe multiplexed over
//            time across multiple threads. The park()/unpark() pair is
//            used to make it avaiable for such multiplexing.
class ThreadLocalAllocBuffer: public CHeapObj{
  friend class VMStructs;
private:
  HeapWord* _start;                              // address of TLAB
  HeapWord* _top;                                // address after last allocation
  HeapWord* _pf_top;                             // allocation prefetch watermark
  HeapWord* _end;                                // allocation end (excluding alignment_reserve)
  size_t    _desired_size;                       // desired size   (including alignment_reserve)
  size_t    _refill_waste_limit;                 // hold onto tlab if free() is larger than this复制代码

In essence, TLAB management is to rely on three pointers: start, end, top.

start and end of the marked area is managed TLAB Eden, this area will not be used by other threads allocate memory, top assigned pointer position start at the beginning, as memory allocation, slowly approaching the end triggered when hit End TLAB Refill .

Thus memory Eden structure substantially:


Second, the new generation of Survivor region .

When the Eden area out of memory triggers Minor GC, also known as the new generation GC, survived in Minor GC object is copied to the Survivor region.

I think the role of Survivor region is to avoid premature triggering Full GC. If there is no Survivor, Eden District, once for each Minor GC regard the object directly to the old year old's lack of memory will soon lead to Full GC.

The new generation has two Survivor areas , I think the role of two Survivor is to improve performance and avoid memory fragmentation.

At any time, there is always a Survivor is empty, and in the event of Minor GC, and the other will Eden Survivor live objects are copied to the empty Survivor, thereby avoiding memory fragmentation.

The new generation memory structure generally:

Third, the old years .

Old's placed the long life cycle of an object, usually copied from Survivor region over the target, but when the object is too large, contiguous memory storage can not be used in the new generation, then the large object will be directly allocated in the old years on.

In general, ordinary objects are allocated on the TLAB, larger object, directly assigned to other memory areas in the Eden area, and oversized objects directly allocated in the old era.

Fourth, the permanent behalf .

As previously mentioned, the concept of old age in the early Hotspot JVM, the year old metadata for storing Java classes, constant pool, Intern. Strings and the like.

After JDK8, it will remove the old years, introduced the concept of metadata area.

Fifth, Vritual space .

As mentioned above, you can use Xms with Xmx to specify minimum and maximum heap space.

If Xms less than Xmx, heap size does not extend directly to the ceiling, but keep waiting for the memory part of the growing demand for redistribution to the new generation. Vritual space is reserved for this part of the memory area.

In summary, you can draw structures within the Java heap memory generally:

Through a number of parameters, you can specify a size of the heap memory area:

-Xmx value specifies the maximum heap size

-Xms value specified minimum initial heap size

-XX: NewSize = value specifies the size of the new generation of

-XX: NewRatio = value size ratio's old and new generation.


By default, this ratio is 2, that's old is twice the size of the new generation. Old's too much time, Full GC time will be very long;


Years old and too small, it is easy to trigger Full GC, Full GC frequency is too high, this is the influence of this parameter will result.


-XX: SurvivorRation = value size ratio Srivivor provided with the Eden, if the value of 8, is representative of a Survivor Eden 1/8, 1/10 of the whole new generation.


Commonly used performance monitoring and fault location tools What?

Performance analysis system, CPU, memory and IO is the main item of concern.

Many times service problems, will be reflected in the emergence of these three, such as CPU soared out of memory and other OOM occurs, this time need to use the corresponding tools to monitor the performance, to locate the problem.

For monitoring CPU, first you can use top command to view, top view Here is a screenshot of the load:

load average represents 1 minute, 5 minutes, 15 minutes system load average , these three numbers, based on the system load is large or small.

When the CPU is completely idle, the average load is 0; when the CPU workload saturated average load 1. Thus the lower the average load of these three values, the less representative of the system load.

So when the system load is heavy you can see it?

This article (Understanding Linux CPU Load - when should you be worried) was interpreted very popular.

If the computer has only one CPU, the CPU as a one-way bridge, the bridge has only one lane, and all cars must pass through this bridge. Then

  • System load, indicates that there is no car on the bridge

  • 0.5 system load, means that half a car on the bridge section

  • System load 1, meaning the bridge road has been filled car

  • 1.7 system load, the bridge represents the car is full (100%), as well as 70% of cars waiting from the bridge by:

From the screenshot you can see the top command of the three values ​​of the machine load average is very low. If these three values ​​are very high, such as more than 50% or 60%, should attract attention.

From the time dimension, if found to slowly increase the CPU load, also need to be vigilant.

Use other memory, CPU and other performance monitoring tools to a mind map to show:

Specific reference line failures can use Java to think the idea from a positioning problem

End


Source: https: //www.cnblogs.com/QG-whz/p/9636366.html

This article belongs to the author of all

Long press the map two-dimensional code, civet cats immediate concern [technical] nest

Ali, Jingdong, the US group, beating top technical experts based in bytes

IT people to create a "temperature" technology nest!


Reproduced in: https: //juejin.im/post/5cf01d56f265da1b7f296374

Guess you like

Origin blog.csdn.net/weixin_33963594/article/details/91482055