Interviewers often ask Series: Java virtual machine memory of the four questions, in which the!

topic

  • JVM memory area is how divided?
  • OOM which may occur in the area?
  • Heap memory structure is kind of how?
  • Commonly used performance monitoring and fault location tools What?

1.JVM area of ​​memory is how divided?

JVM memory division, some areas are private to the thread, some belong to the entire JVM process; some areas will throw an exception OOM, some do not understand the divided memory areas and features of the JVM, is positioning line memory problems The basics. 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. The memory area is the only area of ​​memory does not provide any OOM situation in the Java Virtual Machine Specification.

Second, Java virtual machine stack (Java Virtal Machine Stack), also belongs to the same thread private area, each thread will create a virtual machine stack at the time of creation, consistent with the life cycle of a thread, a thread exits, the thread stack virtual machines also recovered. 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, 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 district method (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, will throw an OutOfMemoryError. 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 an OutOfMemoryError.

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 a constant pool entry. The main constant pool constants stored into two categories:

Literals (the Literal), such as text strings, final constant value
symbol references, some stored constants associated with the compiled Java, unlike C ++ because the process as there are connected, so the field of these reference symbols will need to be converted at runtime in order to get the real memory address entry.
class file constant pool, also called 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:

Interviewers often ask Series: Java virtual machine memory of the four questions, in which the!

2.OOM may occur in which areas?

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. Heap memory shortage is one of the most common causes of sending OOM, if not complete memory object instances allocated on the heap, and the heap can not be extended again, will throw an OutOfMemoryError. 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 request thread stack size is larger than the allocated stack is thrown StackOverFlowError errors, such conduct will not stop a recursive call; if 2. virtual machines can be 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 corresponding to the letter "java.lang.OutOfMemoryError: PermGen space"

Interviewers often ask Series: Java virtual machine memory of the four questions, in which the!

Heap memory structure is kind of how?

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 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 heap dump file may be green (Heap Dump) file, if it is in the linux, heap dump file can be locally pulled using Eclipse MAT analysis, 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: how structures within the heap is 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 Eden, preferentially allocated objects in the region, and can assign a private JVM cache area for each thread, referred TLAB (Thread Local Allocation Buffer), to avoid the use of multiple threads need to increase the allocation of memory lock mechanisms affecting the distribution rate. TLAB allocated on the heap, located in Eden. 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<mtThread> {

  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

从本质上来说,TLAB的管理是依靠三个指针:start、end、top。start与end标记了Eden中被该TLAB管理的区域,该区域不会被其他线程分配内存所使用,top是分配指针,开始时指向start的位置,随着内存分配的进行,慢慢向end靠近,当撞上end时触发TLAB refill。因此内存中Eden的结构大体为:

Interviewers often ask Series: Java virtual machine memory of the four questions, in which the!

第二、新生代的Survivor区域。当Eden区域内存不足时会触发Minor GC,也称为新生代GC,在Minor GC存活下来的对象,会被复制到Survivor区域中。我认为Survivor区的作用在于避免过早触发Full GC。如果没有Survivor,Eden区每进行一次Minor GC都把对象直接送到老年代,老年代很快便会内存不足引发Full GC。新生代中有两个Survivor区,我认为两个Survivor的作用在于提高性能,避免内存碎片的出现。在任何时候,总有一个Survivor是empty的,在发生Minor GC时,会将Eden及另一个的Survivor的存活对象拷贝到该empty Survivor中,从而避免内存碎片的产生。新生代的内存结构大体为:

Interviewers often ask Series: Java virtual machine memory of the four questions, in which the!

第三、老年代。老年代放置长生命周期的对象,通常是从Survivor区域拷贝过来的对象,不过当对象过大的时候,无法在新生代中用连续内存的存放,那么这个大对象就会被直接分配在老年代上。一般来说,普通的对象都是分配在TLAB上,较大的对象,直接分配在Eden区上的其他内存区域,而过大的对象,直接分配在老年代上。

第四、永久代。如前面所说,在早起的Hotspot JVM中有老年代的概念,老年代用于存储Java类的元数据、常量池、Intern字符串等。在JDK8之后,就将老年代移除,而引入元数据区的概念。

第五、Vritual空间。前面说过,可以使用Xms与Xmx来指定堆的最小与最大空间。如果Xms小于Xmx,堆的大小不会直接扩展到上限,而是留着一部分等待内存需求不断增长时,再分配给新生代。Vritual空间便是这部分保留的内存区域。

那么综上所述,可以画出Java堆内的内存结构大体为:

Interviewers often ask Series: Java virtual machine memory of the four questions, in which the!

通过一些参数,可以来指定上述的堆内存区域的大小:

  • -Xmx value 指定最大的堆大小
  • -Xms value 指定初始的最小堆大小
  • -XX:NewSize = value 指定新生代的大小
  • -XX:NewRatio = value 老年代与新生代的大小比例。默认情况下,这个比例是2,也就是说老年代是新生代的2倍大。老年代过大的时候,Full GC的时间会很长;老年代过小,则很容易触发Full GC,Full GC频率过高,这就是这个参数会造成的影响。
  • -XX:SurvivorRation = value . 设置Eden与Srivivor的大小比例,如果该值为8,代表一个Survivor是Eden的1/8,是整个新生代的1/10。

常用的性能监控与问题定位工具有哪些?

在系统的性能分析中,CPU、内存与IO是主要的关注项。很多时候服务出现问题,在这三者上会体现出现,比如CPU飙升,内存不足发生OOM等,这时候需要使用对应的工具,来对性能进行监控,对问题进行定位。

对于CPU的监控,首先可以使用top命令来进行查看,下面是使用top查看负载的一个截图:

Interviewers often ask Series: Java virtual machine memory of the four questions, in which the!

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. Therefore, the lower the average load these three values, the smaller the representatives of system load, it can be seen when the system load is heavy 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

Interviewers often ask Series: Java virtual machine memory of the four questions, in which the!

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

Interviewers often ask Series: Java virtual machine memory of the four questions, in which the!

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

Interviewers often ask Series: Java virtual machine memory of the four questions, in which the!

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

Interviewers often ask Series: Java virtual machine memory of the four questions, in which the!

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:

Interviewers often ask Series: Java virtual machine memory of the four questions, in which the!

Specific reference line failures can use Java to think from a problem common causes.

Reprinted from the public No. Fang Zhipeng

Guess you like

Origin blog.51cto.com/14570694/2453644