Summary of JVM core knowledge points and JVM interview questions

foreword

About the knowledge points of JVM series interviews, I summarized a mind map and shared it with you

 

memory structure

thread shared area

Heap (used to store object instances)

1. The new generation

(1) Eden District

(2) Survivor (from) area (Survivor is set to reduce objects sent to the old age)

(3) Survivor(to) area (two Survivor areas are set up to solve the problem of fragmentation)

(4)eden:survivor:survivor = 8:1:1

2. Old age

Old Generation: New Generation = 2:1

method area

1. Runtime constant pool

(1) The constant pool in the Class file (various literal and symbolic references generated by the compiler) will be placed in this area after the class is loaded.

(2) Store information

symbol reference

1) Symbol references contain constants

  • class symbol reference

  • method symbol reference

  • field symbol reference

2) Concept explanation

When a java class (assumed to be the People class) is compiled into a class file, if the People class refers to the Tool class, but the People class does not know the actual memory address of the referenced class during compilation, so symbolic references can only be used instead. When the class loader loads the People class, the actual memory address of the Tool class can be obtained through the virtual machine at this time, so the symbol org.simple.Tool can be replaced with the actual memory address of the Tool class, and the address can be directly referenced. That is, the symbol reference is used to replace the reference class at compile time, and the actual address of the reference class is obtained through the virtual machine at load time. Use a set of symbols to describe the referenced target. The symbol can be any form of literal value, as long as it can be used to locate the target without ambiguity. Symbolic references have nothing to do with the memory layout implemented by the virtual machine, and the referenced targets are not necessarily loaded into memory.

Literal

  • Text string (String a = "abc", this abc is the literal value)

  • Eight basic types (int a = 1; this 1 is the literal value)

  • Constants declared final

2. Static variables

3. final type constant

4. Class information

  • the fully qualified name of the class

  • return type

  • Modifiers (public, private...)

  • variable name

  • method name

  • method code

  • The fully qualified name of the immediate superclass of this type (unless the type is interface or java.lang.Object, in which case there is no superclass)

  • an ordered list of the direct interfaces of the class

thread private area

virtual machine stack

1. Stack frame

(1) Dynamic link

  • The process of parsing and linking symbolic references and direct references at runtime is called dynamic linking.

  • The premise is that each stack frame must contain a reference to the runtime constant pool to support the implementation of dynamic linking.

(2) Operand stack

Save the data during the execution of the Java virtual machine

(3) Local variable table

1) The memory space required by the local variable table is allocated during compilation. When entering a method, how much local variable space the method needs to allocate in the frame is completely determined, and the local variable table will not be changed during the running of the method. size.

2) Stored information

  • basic data type

  • object reference

  • returnAddressType

(4) Method return address

1) Where the method is called

2) The process of method exit is actually equivalent to popping the current stack frame

3) The method exit may contain operations

  • Restore the local variable table and operand stack of the upper method

  • Push the return value (if any) onto the operand stack of the caller's stack frame

  • Adjust the value of the PC counter to point to one instruction after the method call instruction

2. Abnormal

The stack depth requested by the thread is greater than the depth allowed by the virtual machine (StackOverflowError)

When the JVM dynamically expands and cannot apply for enough memory (OutOfMemoryError)

When compiling the program code, how much local variable table and how deep the operand stack needs to be in the stack frame have been completely determined, and written into the Code attribute of the method table, so how much memory does a stack frame need to allocate, It will not be affected by variable data during program runtime, but only depends on the specific virtual machine implementation.

native method stack

Similar to the virtual machine stack, the difference is that the local method stack serves the used Native method

program counter

1. If the thread is executing a Java method, indicate the number of code bytecode lines executed by the current thread

2. This memory area is the only area where OutOfMemoryError will not occur.

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

The life cycle and thread of the above three areas are the same

direct memory

1. Use Native function library to directly allocate off-heap memory

2. It is not part of the JVM runtime data area, but it will be frequently used

3. Avoid copying data back and forth between the Java heap and the Native heap, which can improve efficiency

memory allocation

Objects are allocated in the Eden area first

In most cases, objects are allocated in the Eden area of ​​the young generation. When the Eden area does not have enough space to allocate, the virtual machine will initiate a Minor GC.

Large objects go directly to the old generation

The most typical large objects are the kind of very long strings and arrays.

Long-term survivors enter the elderly area

If the object is still alive after the first Minor GC after being born in Eden, and can be accommodated by Survivor, it will be moved to the Survivor space, and the age of the object will be set to 1. Every time the object survives a Minor GC in the Survivor area , the age is increased by 1, and when its age increases to a certain level (the default is 15)_, it will be promoted to the old generation.

Object age dynamic determination

If the combined size of all objects of the same age in the Survivor space is greater than half of the Survivor space, objects with an age greater than or equal to this age can directly enter the old age

Space Allocation Guarantee

Before Minor GC occurs, the virtual machine first checks whether the maximum available continuous space in the old generation is greater than the total space of all objects in the new generation. If this condition is true, then Minor GC can ensure that it is safe. If not, the virtual machine checks whether the HandlePromotionFailure setting value allows guarantee failure. If it is allowed, it will continue to check whether the maximum available continuous space in the old generation is greater than the average size of objects promoted to the old generation. If it is larger, it will try to perform a Minor GC. Although this Minor GC is risky, if the guarantee fails A Full GC will be performed; if it is less than, or the HandlePromotionFailure setting does not allow risk, then a Full GC should also be performed at this time.

memory recovery

Minor GC

features

Occurs in the new generation, occurs more frequently, and executes faster

Triggering conditions

  • Lack of space in Eden

  • Space Allocation Guarantee

Full GC

features

Occurs in the old generation, occurs less frequently, and executes slower

Triggering conditions

  • Call System.gc()

  • Insufficient space in the old generation area

  • Space allocation guarantee failed

  • JDK 1.7 and previous permanent generation (method area) space is insufficient

  • When CMS GC handles floating garbage, if the new generation space is insufficient, the space allocation guarantee mechanism will be adopted, and if the old generation space is insufficient, Full GC will be triggered

out of memory

When the program is applying for memory, there is not enough memory space

The structure of memory overflow

heap overflow

OutOfMemoryError: Keep creating objects

stack overflow

StackOverflowError: Incrementing local variable table, e.g. unreasonable recursion

OutOfMemoryError: Keep creating threads

Method area and runtime constant pool overflow

OutOfMemoryError: Continuously add constants to the constant pool through the String.intern() method, such as String.valueOf(i++).intern()

Native memory overflows directly

memory leak

After the program applies for memory, it cannot release the requested memory space

reason

Long-lived objects hold references to short-lived objects

For example, if ArrayList is set as a static variable, the objects in the container will not be released before the end of the program, resulting in memory leaks

connection not closed

Such as database connection, network connection and IO connection, etc., only after the connection is closed, the garbage collector will recycle the corresponding object.

Inappropriate variable scope

For example, 1. The scope of the definition of a variable is greater than its scope of use, 2. If the object is not set to null in time

Inner class holds outer class

This way of creating non-static inner classes in Java will implicitly hold references to the outer class, and by default this reference is a strong reference. Therefore, if the life cycle of the inner class is longer than the life cycle of the outer class, the program is very prone to memory leaks

Solution

  • Define the inner class as static

  • Use static variables to refer to instances of anonymous inner classes

  • Or put the instantiation operation of the anonymous inner class into the static method of the outer class

Hash value changes

In a collection, if the fields involved in calculating the hash value in the object are modified, the current object cannot be deleted from the collection alone, resulting in a memory leak

common interview questions

1. Will there be a memory leak in java? Please describe it briefly.

meeting. Memory leaks may occur when implementing the heaped data structure yourself.

2. In 64-bit JVM, what is the maximum length of int?

In Java, the length of an int type variable is a fixed value, which is 32 bits regardless of the platform. That is to say, in the 32-bit and 64-bit Java virtual machines, the length of the int type is the same.

3. What is the difference between Serial and Parallel GC?

Both Serial and Parallel will cause stop-the-world when GC is executed. The main difference between them is that the serial collector is the default copy collector, and there is only one thread when executing GC, while the parallel collector uses multiple GC threads to execute.

4. For 32-bit and 64-bit JVM, what is the maximum length of int type variable?

In the 32-bit and 64-bit JVM, the length of the int type variable is the same, both are 32 bits or 4 bytes.

5. What is the difference between WeakReference and SoftReference in Java?

Although both WeakReference and SoftReference are beneficial to improve the efficiency of GC and memory, once WeakReference loses the last strong reference, it will be recycled by GC, while soft reference cannot prevent it from being recycled, but it can be delayed until the JVM runs out of memory.

6. What does the JVM option -XX:+UseCompressedOops do? why use

When you migrate your application from a 32-bit JVM to a 64-bit JVM, the heap memory will suddenly increase, nearly doubling, due to the increase in object pointers from 32-bit to 64-bit. This will also adversely affect data in the CPU cache (which is much smaller than RAM). Because the main motivation for migrating to a 64-bit JVM is that the maximum heap size can be specified, and a certain amount of memory can be saved by compressing OOP. With the -XX:+UseCompressedOops option, the JVM will use 32-bit OOP instead of 64-bit OOP.

7. How to judge whether the JVM is 32-bit or 64-bit through a Java program?

You can check some system properties like sun.arch.data.model or os.arch to get this information.

8. What is the maximum heap memory of 32-bit JVM and 64-bit JVM respectively?

In theory, the 32-bit JVM heap memory can reach 2^32, which is 4GB, but in reality it will be much smaller than this. It varies between different operating systems, such as about 1.5GB for Windows and about 3GB for Solaris. The 64-bit JVM allows specifying the maximum heap memory, which can theoretically reach 2^64, which is a very large number. In fact, you can specify the heap memory size to 100GB. Even some JVMs, such as Azul, have heap memory up to 1000G.

9. What is the difference between JRE, JDK, JVM and JIT?

JRE stands for Java run-time and is required to run Java references. JDK stands for Java development kit (Java development kit), which is a Java program development tool, such as a Java compiler, which also includes a JRE. JVM stands for Java virtual machine (Java virtual machine), which is responsible for running Java applications. JIT stands for Just In Time compilation. When the number of code executions exceeds a certain threshold, it will convert Java bytecode into native code. For example, the main hot code will be replaced with native code, which is beneficial Significantly improve the performance of Java applications.

10. Explain Java heap space and GC?

When a Java process is started by the Java command, memory is allocated for it. Part of the memory is used to create the heap space, and when an object is created in the program, memory is allocated from the space. GC is a process inside the JVM that reclaims the memory of invalid objects for future allocations.

memory area

11. JVM memory area

The JVM memory area is mainly divided into thread private area [program counter, virtual machine stack, local method area], thread shared area [JAVA heap, method area], and direct memory.

The life cycle of the thread private data area is the same as that of the thread, and it is created/destroyed depending on the start/end of the user thread (in the Hotspot VM, each thread is directly mapped to the local thread of the operating system, so the storage/non-existence of this part of the memory area follows native thread life/death correspondence).

The thread shared area is created/destroyed with the startup/shutdown of the virtual machine.

Direct memory is not part of the JVM runtime data area, but it is also frequently used: NIO introduced in JDK 1.4 provides an IO method based on Channel and Buffer, which can use Native function library to directly allocate off-heap memory, and then use The DirectByteBuffer object operates as a reference to this memory (see: Java I/O Extensions for details), which avoids copying data back and forth between the Java heap and the Native heap, so performance can be significantly improved in some scenarios.

12. Program counter (thread private)

A small memory space is the line number indicator of the bytecode executed by the current thread. Each thread must have an independent program counter. This type of memory is also called "thread private" memory.

If the java method is being executed, what the counter records is the address of the virtual machine bytecode instruction (the address of the current instruction). If it is still a Native method, it is empty.

This memory region is the only one that does not specify any OutOfMemoryError conditions in the virtual machine.

13. Virtual machine stack (thread private)

It is a memory model that describes the execution of java methods. When each method is executed, a stack frame (Stack Frame) is created to store information such as local variable tables, operand stacks, dynamic links, and method exits. The process of each method from invocation to execution completion corresponds to the process of a stack frame being pushed into the virtual machine stack to popped out of the stack.

Stack frame (Frame) is a data structure used to store data and some process results, and is also used to handle dynamic linking (Dynamic Linking), method return value and exception dispatch (Dispatch Exception). Stack frames are created when a method is called and destroyed when the method ends—whether the method completes normally or completes abnormally (throwing an exception that was not caught within the method) counts as the end of the method.

14. Local method area (thread private)

The local method area is similar to the Java Stack, the difference is that the virtual machine stack serves for executing Java methods, while the local method stack serves for Native methods. If a VM implementation uses the C-linkage model to support Native calls, then the stack will be A C stack, but HotSpot VM directly combines the local method stack and the virtual machine stack into one.

15. Can you guarantee GC execution?

No, although you can call System.gc() or Runtime.gc(), there is no way to guarantee GC execution.

16. How to get the memory used by the Java program? % of heap usage?

The remaining memory, total memory and maximum heap memory can be obtained through memory-related methods in the java.lang.Runtime class. You can also get the percentage of heap usage and the remaining space of heap memory through these methods. The Runtime.freeMemory() method returns the number of bytes of the remaining space, the Runtime.totalMemory() method returns the number of bytes of the total memory, and the Runtime.maxMemory() returns the number of bytes of the maximum memory.

17. What is the difference between heap and stack in Java?

The heap and stack in the JVM belong to different memory areas and are used for different purposes. The stack is often used to hold method frames and local variables, while objects are always allocated on the heap. The stack is usually smaller than the heap and is not shared between multiple threads, while the heap is shared by all threads of the entire JVM.

18. Describe the principle mechanism of JVM loading class files

The loading of classes in the JVM is implemented by the class loader (ClassLoader) and its subclasses. The various loaders in Java are an important component of the Java runtime system, which is responsible for finding and loading class files at runtime. the type.

Due to the cross-platform nature of Java, the compiled Java source program is not an executable program, but one or more class files. When a Java program needs to use a certain class, the JVM will ensure that the class has been loaded, connected (validated, prepared and parsed) and initialized. Class loading refers to reading the data in the .class file of the class into the memory, usually by creating a byte array and reading it into the .class file, and then generating the Class object corresponding to the loaded class.

After the loading is complete, the Class object is not complete, so the class at this time is not yet available. When the class is loaded, it enters the connection phase, which includes three steps: verification, preparation (allocating memory for static variables and setting default initial values) and resolution (replacing symbolic references with direct references). Finally, the JVM initializes the class, including: 1) If the class has a direct parent class and the class has not been initialized, then initialize the parent class first; 2) If there are initialization statements in the class, execute these initialization statements in sequence.

Class loading is done by class loaders, which include: root loader (BootStrap), extension loader (Extension), system loader (System) and user-defined class loader (java.lang.ClassLoader's Subclass).

Starting from Java 2 (JDK 1.2), the class loading process adopts the parent delegation mechanism (PDM). PDM better guarantees the security of the Java platform. In this mechanism, the Bootstrap that comes with the JVM is the root loader, and other loaders have and only have one parent class loader. The loading of the class first requests the parent class loader to load, and when the parent class loader is helpless, its child class loader will load it by itself. The JVM does not provide references to Bootstrap to Java programs. The following is about several classes

Description of the loader:

(1) Bootstrap: generally implemented with local code, responsible for loading the JVM basic core class library (rt.jar);

(2) Extension: Load the class library from the directory specified by the java.ext.dirs system property, and its parent loader is Bootstrap;

(3) System: Also known as the application class loader, its parent class is Extension. It is the most widely used class loader. It gets from environment variable classpath or system property

The class recorded in the directory specified by java.class.path is the default parent loader of the user-defined loader.

garbage collector

19. What is GC? Why is there a GC?

GC means garbage collection. Memory handling is a place where programmers are prone to problems. Forgotten or wrong memory recovery will lead to instability or even crash of the program or system. The GC function provided by Java can automatically monitor whether the object exceeds the scope to achieve For the purpose of automatically reclaiming memory, the Java language does not provide an explicit operation method to release allocated memory. Java programmers don't have to worry about memory management because the garbage collector takes care of it automatically. To request garbage collection, one of the following methods can be called: System.gc() or Runtime.getRuntime().gc() , but the JVM can mask out-of-line garbage collection calls.

Garbage collection can effectively prevent memory leaks and effectively use available memory. The garbage collector usually runs as a separate low-priority thread. Under unpredictable circumstances, objects that have died or have not been used for a long time in the memory heap are cleared and recycled. Programmers cannot call the garbage collector in real time. An object or all objects are garbage collected. In the early days of Java's birth, garbage collection was one of the biggest highlights of Java, because server-side programming needs to effectively prevent memory leaks. However, with the passage of time, Java's garbage collection mechanism has become something that has been criticized. Mobile smart terminal users usually feel that the iOS system has a better user experience than the Android system. One of the deep-seated reasons is the unpredictability of garbage collection in the Android system.

20. Heap (Heap-thread sharing) - runtime data area

It is a memory area shared by threads. The created objects and arrays are stored in the Java heap memory, and it is also the most important memory area for garbage collection by the garbage collector. Since modern VMs use generational collection algorithms, the Java heap can also be subdivided from the perspective of GC: the new generation (Eden area, From Survivor area, and To Survivor area) and the old generation.

21. Method area/permanent generation (thread sharing)

That is what we often call the Permanent Generation (Permanent Generation), which is used to store data such as class information loaded by the JVM, constants, static variables, and code compiled by the compiler. HotSpot VM extends GC generational collection to the method area, That is, the permanent generation of the Java heap is used to implement the method area, so that the HotSpot garbage collector can manage this part of memory just like the Java heap, without having to develop a special memory manager for the method area (the main goal of the permanent memory recovery is for constant pool recycling and type unloading, so the gains are generally small).

The Runtime Constant Pool is part of the method area. In addition to the class version, fields, methods, interfaces and other descriptions in the Class file, there is also a constant pool (Constant Pool Table), which is used to store various literals and symbol references generated during compilation. This part The content will be stored in the runtime constant pool in the method area after the class is loaded. The Java virtual machine has strict regulations on the format of each part of the Class file (including the constant pool naturally). The data that each byte is used to store must meet the requirements of the specification, so that it will be recognized by the virtual machine. Load and execute.

22. JVM runtime memory

From the perspective of GC, the Java heap can also be subdivided into: the new generation (Eden area, From Survivor area and To Survivor area) and the old generation.

23. The new generation

Is used to store new objects. Generally occupy 1/3 space of the heap. Due to the frequent creation of objects, the new generation will frequently trigger MinorGC for garbage collection. The new generation is divided into three areas: Eden area, SurvivorFrom, and SurvivorTo.

Eden District

The birthplace of new Java objects (if the newly created object takes up a lot of memory, it will be directly allocated to the old generation). When the memory in the Eden area is not enough, MinorGC will be triggered to perform a garbage collection on the new generation area.

ServivorFrom

The survivors of the last GC are the ones to be scanned for this GC.

ServivorTo

Survivors from a MinorGC process are kept.

The process of MinorGC (copy->clear->swap)

MinorGC uses a replication algorithm.

(1) eden, servantorFrom copied to ServicorTo, age +1

First, copy the surviving objects in the Eden and SurvivorFrom areas to the ServicorTo area (if there is an object's age and reach the old age standard, then assign it to the old generation area), and at the same time, add 1 to the age of these objects (if the ServicorTo is not enough space put it in the elderly area);

(2) Empty eden, servicerFrom

Then, clear the objects in Eden and ServicorFrom;

(3) ServicorTo and ServicorFrom interchange

Finally, ServicorTo and ServicorFrom are interchanged, and the original ServicorTo becomes the ServicorFrom area in the next GC.

24. Old generation

It mainly stores long-lived memory objects in the application.

Objects in the old generation are relatively stable, so MajorGC will not be executed frequently. MinorGC is generally performed before MajorGC, so that objects in the new generation are promoted to the old generation, and it is triggered when there is not enough space. When it is impossible to find a large enough contiguous space to allocate to newly created larger objects, it will also trigger a MajorGC in advance for garbage collection to make room.

MajorGC uses a mark-clearing algorithm: first scan all the old ages once, mark out the surviving objects, and then recycle the unmarked objects. ajorGC takes a long time because it needs to be scanned and recycled. MajorGC will generate memory fragmentation. In order to reduce memory loss, we generally need to merge or mark it out for direct allocation next time. When the old generation is too full to fit, an OOM (Out of Memory) exception will be thrown.

25. Permanent generation

Refers to the permanent storage area of ​​the memory, which mainly stores Class and Meta (metadata) information. When Class is loaded, it is put into the permanent area. It is different from the area where instances are stored. GC will not change the permanent area during the running of the main program. Area to be cleaned. Therefore, this also causes the area of ​​the permanent generation to become full as the number of loaded classes increases, eventually throwing an OOM exception.

26. JAVA8 and metadata

In Java8, the permanent generation has been removed and replaced by an area called the "metadata area" (metaspace). The essence of the metaspace is similar to that of the permanent generation. The biggest difference between the metaspace and the permanent generation is that the metaspace is not in the virtual machine, but uses local memory. Therefore, by default, the size of the metaspace is limited only by local memory. Class metadata is put into nativememory, string pool and class static variables are put into java heap, so how much class metadata can be loaded is no longer controlled by MaxPermSize, but by the actual available space of the system.

27. Reference counting

In Java, references and objects are associated. If you want to manipulate objects, you must use references. Therefore, it is obvious that a simple way is to judge whether an object can be recycled by reference counting. Simply put, if an object does not have any references associated with it, that is, their reference counts are not 0, it means that the object is unlikely to be used again, then this object is a recyclable object.

28. Accessibility Analysis

In order to solve the circular reference problem of the reference counting method, Java uses the method of reachability analysis. Search through a series of "GC roots" objects as a starting point. An object is said to be unreachable if there is no reachable path between "GC roots" and the object. It should be noted that unreachable objects are not equivalent to recyclable objects, and it takes at least two marking processes for unreachable objects to become recyclable objects. If it is still a recyclable object after two marks, it will face recycling.

29. Mark-Sweep algorithm (Mark-Sweep)

The most basic garbage collection algorithm is divided into two stages, marking and clearing. The marking phase marks all objects that need to be reclaimed, and the cleanup phase reclaims the space occupied by the marked objects. as shown in the picture

From the figure, we can see that the biggest problem of this algorithm is that the memory fragmentation is severe, and there may be a problem that large objects cannot find available space in the future.

30. Copying algorithm (copying)

An algorithm proposed to solve the defect of Mark-Sweep algorithm memory fragmentation. Divide the memory into two blocks of equal size according to the memory capacity. Only use one of them each time. When this memory is full, copy the surviving objects to another, and clear the used memory, as shown in the figure:

Although this algorithm is simple to implement, has high memory efficiency, and is not prone to fragmentation, the biggest problem is that the available memory is compressed to half of the original. And if the number of surviving objects increases, the efficiency of the Copying algorithm will be greatly reduced.

31. Mark-Compact

Combining the above two algorithms, it is proposed in order to avoid defects. The marking phase is the same as the Mark-Sweep algorithm. After marking, the objects are not cleaned up, but the surviving objects are moved to one end of the memory. Objects outside the end boundaries are then cleared. As shown in the picture:

32. Generational collection algorithm

The generational collection method is currently adopted by most JVMs. Its core idea is to divide the memory into different domains according to the different life cycles of the objects. Generally, the GC heap is divided into the old generation (Tenured/Old Generation) and The new generation (YoungGeneration). The characteristic of the old generation is that only a small number of objects need to be recycled each time garbage collection is performed. The characteristic of the new generation is that a large amount of garbage needs to be recycled each time garbage collection is performed. Therefore, different algorithms can be selected according to different regions.

33. New Generation and Replication Algorithm

At present, the GC of most JVMs adopts the Copying algorithm for the new generation, because each garbage collection in the new generation needs to recover most of the objects, that is, there are fewer operations to be copied, but the new generation is usually not divided according to 1:1. Generally, the new generation is divided into a larger Eden space and two smaller Survivor spaces (From Space, To Space). Each time the Eden space and one of the Survivor spaces are used, when recycling, the two spaces are The objects that are still alive in the space are copied to another Survivor space.

34. Old Generation and Mark Replication Algorithm

The old generation uses the Mark-Compact algorithm because only a small number of objects are recycled each time.

(1) The Permanet Generation (Permanet Generation) in the method area mentioned by the JAVA virtual machine is used to store classes, constants, method descriptions, etc. The collection of the permanent generation mainly includes obsolete constants and useless classes.

(2) The memory allocation of objects is mainly in the Eden Space of the new generation and the From Space of the Survivor Space (where Survivor currently stores objects), and in a few cases, it will be directly allocated to the old generation.

(3) When the Eden Space and From Space of the new generation are insufficient, a GC will occur. After the GC, the surviving objects in the Eden Space and From Space areas will be moved to To Space, and then Eden Space and From Space will be cleaned up.

(4) If To Space cannot store an object enough, store this object in the old generation.

(5) After GC, Eden Space and To Space are used, and the cycle repeats.

(6) When the object escapes GC once in Survivor, its age will be +1. By default, objects whose age reaches 15 will be moved to the old generation.

35. JAVA strong reference

The most common one in Java is strong reference, assigning an object to a reference variable, this reference variable is a strong reference. When an object is referenced by a strong reference variable, it is in a reachable state, and it cannot be recycled by the garbage collection mechanism, even if the object will never be used by the JVM in the future. Therefore, strong references are one of the main causes of Java memory leaks.

36. JAVA soft reference

Soft references need to be implemented with the SoftReference class. For an object with only soft references, it will not be recycled when the system memory is sufficient, and it will be recycled when the system memory space is insufficient. Soft references are often used in memory-sensitive programs.

37. JAVA weak reference

Weak references need to be implemented with the WeakReference class, which has a shorter lifetime than soft references. For objects with only weak references, as long as the garbage collection mechanism runs, no matter whether the JVM's memory space is sufficient or not, the objects occupied by the object will always be recycled. Memory.

38. JAVA virtual reference

The phantom reference needs to be implemented by the PhantomReference class, which cannot be used alone, and must be used in conjunction with the reference queue. The main purpose of phantom references is to track the status of objects being garbage collected.

39. Generational collection algorithm

The current mainstream VM garbage collection adopts the "Generational Collection" (Generational Collection) algorithm, which divides the memory into several blocks according to the life cycle of the object, such as the new generation, old generation, and permanent generation in the JVM. The most appropriate GC algorithm can be used according to the characteristics of each age

40. In the new generation-replication algorithm

Every garbage collection can find that a large number of objects are dead, and only a small number of them are alive. Therefore, if the copy algorithm is selected, the collection can be completed only by paying the copy cost of a small number of surviving objects

41. In the old generation - mark finishing algorithm

Because the object has a high survival rate and there is no extra space for its allocation guarantee, it is necessary to use the "mark-clean" or "mark-organize" algorithm to recycle, without memory copying, and free memory directly.

42. Partition collection algorithm

The partition algorithm divides the entire heap space into different continuous small areas, each of which is used independently and recycled independently. The advantage of this is that it can control how many small areas are recycled at a time, and according to the target pause time, a reasonable number of small areas can be recovered each time Small areas (rather than the entire heap), thereby reducing the pause generated by a GC.

43. GC garbage collector

The Java heap memory is divided into two parts: the new generation and the old generation. The new generation mainly uses the copy and mark-sweep garbage collection algorithm; the old generation mainly uses the mark-sort garbage collection algorithm. Each generation provides a variety of different garbage collectors. The garbage collectors of the Sun HotSpot virtual machine in JDK1.6 are as follows:

44. Serial garbage collector (single thread, copy algorithm)

Serial (continuous in English) is the most basic garbage collector, using the copy algorithm, and was the only garbage collector in the new generation before JDK1.3.1. Serial is a single-threaded collector. It not only uses one CPU or one thread to complete the garbage collection work, but also must suspend all other working threads until the garbage collection ends.

Although the Serial garbage collector needs to suspend all other worker threads during the garbage collection process, it is simple and efficient. For a limited single CPU environment, there is no thread interaction overhead and the highest single-threaded garbage collection efficiency can be obtained. Therefore, Serial garbage The collector is still the default new generation garbage collector when the java virtual machine runs in Client mode.

45. ParNew Garbage Collector (Serial+Multithreading)

The ParNew garbage collector is actually a multi-threaded version of the Serial collector, and it also uses the copy algorithm. Except for using multi-threading for garbage collection, the rest of the behavior is exactly the same as the Serial collector. The ParNew garbage collector also does the same in the garbage collection process. To suspend all other worker threads.

By default, the ParNew collector opens the same number of threads as the number of CPUs, and the number of threads of the garbage collector can be limited by the -XX:ParallelGCThreads parameter. [Parallel: Parallel]

Although ParNew is almost identical to the Serial collector except for multithreading, the ParNew garbage collector is the default garbage collector for the new generation of many java virtual machines running in Server mode.

46. ​​Parallel Scavenge collector (multi-threaded copy algorithm, efficient)

The Parallel Scavenge collector is also a new generation garbage collector. It also uses the copy algorithm and is also a multi-threaded garbage collector. It focuses on the program to achieve a controllable throughput (Thoughput, the time the CPU is used to run user code /CPU total consumption time, that is, throughput = running user code time/(running user code time+garbage collection time)), high throughput can make the most efficient use of CPU time and complete the calculation tasks of the program as soon as possible. Tasks that operate in the background without requiring much interaction. The adaptive tuning strategy is also an important difference between the ParallelScavenge collector and the ParNew collector.

47. Serial Old collector (single-threaded markup algorithm)

Serial Old is the old generation version of the Serial garbage collector. It is also a single-threaded collector that uses the mark-sort algorithm. This collector also mainly runs on the default client

The default old generation garbage collector for the java virtual machine. In Server mode, there are two main purposes:

(1) Used in conjunction with the new generation of Parallel Scavenge collectors in versions prior to JDK1.5.

(2) As a backup garbage collection scheme using the CMS collector in the old generation. The garbage collection process diagram of the new generation Serial and the old generation Serial Old collocation:

The working principle of the new generation Parallel Scavenge collector is similar to that of the ParNew collector. Both are multi-threaded collectors, both of which use the copy algorithm, and all worker threads need to be suspended during the garbage collection process. The garbage collection process diagram of the new generation ParallelScavenge/ParNew and the old generation Serial Old:

48. Parallel Old Collector (Multithreaded Marking Algorithm)

The Parallel Old collector is an old generation version of Parallel Scavenge, which uses a multi-threaded mark-sort algorithm, which was only available in JDK1.6.

Before JDK1.6, the ParallelScavenge collector used in the new generation can only be used with the Serial Old collector in the old generation. It can only guarantee the throughput of the new generation first, but cannot guarantee the overall throughput. Parallel Old is just for the old generation. It also provides a throughput-first garbage collector. If the system has high throughput requirements, you can give priority to the collocation strategy of the new-generation Parallel Scavenge and the old-generation Parallel Old collector.

The operation process diagram of the parallel Scavenge of the new generation and the Parallel Old collector of the old generation

49. CMS Collector (Multithreaded Mark Sweep Algorithm)

The Concurrent mark sweep (CMS) collector is an old generation garbage collector whose main goal is to obtain the shortest garbage collection pause time. Unlike other old generation mark-sorting algorithms, it uses multi-threaded mark-clear algorithm. Minimal garbage collection pauses can improve user experience for highly interactive programs. The working mechanism of CMS is more complicated than that of other garbage collectors. The whole process is divided into the following 4 stages:

initial mark

Just mark the objects that can be directly associated with GC Roots, which is very fast, and still needs to suspend all worker threads.

concurrent mark

The process of GC Roots tracking works with user threads without suspending worker threads.

relabel

In order to correct the marking record of the part of the object whose marking changes due to the continuous running of the user program during the concurrent marking, it is still necessary to suspend all the worker threads.

concurrent purge

Clear GC Roots unreachable objects and work with user threads without suspending worker threads. Because the garbage collection thread can work concurrently with the user during the longest time-consuming concurrent marking and concurrent clearing process, so in general, the memory recovery of the CMS collector and the user thread are executed concurrently. CMS collector working process

50. G1 Collector

The Garbage first garbage collector is the most cutting-edge achievement in the development of garbage collector theory. Compared with the CMS collector, the two most prominent improvements of the G1 collector are:

(1) Based on the mark-collation algorithm, no memory fragmentation occurs.

(2) Pause time can be controlled very precisely, and low-pause garbage collection can be achieved without sacrificing throughput. The G1 collector avoids full-area garbage collection. It divides the heap memory into several independent areas of fixed size, and tracks the progress of garbage collection in these areas. At the same time, it maintains a priority list in the background. Each time, according to the allowed collection time, The areas with the most garbage are collected first. Area division and priority area recycling mechanism to ensure that the G1 collector can obtain the highest garbage collection efficiency in a limited time

class loading mechanism

51. JVM class loading mechanism

The JVM class loading mechanism is divided into five parts: loading, verification, preparation, parsing, and initialization. Let's take a look at these five processes separately.

load

Loading is a stage in the class loading process. In this stage, a java.lang.Class object representing this class will be generated in the memory as the entry of various data of this class in the method area. Note that it does not have to be obtained from a Class file. It can be read from a ZIP package (such as from a jar package and a war package), or it can be calculated and generated at runtime (dynamic proxy), or it can be generated by other File generation (such as converting JSP files into corresponding Class classes).

verify

The main purpose of this stage is to ensure that the information contained in the byte stream of the Class file meets the requirements of the current virtual machine and will not endanger the safety of the virtual machine itself.

Prepare

The preparation stage is the stage of formally allocating memory for class variables and setting the initial value of class variables, that is, allocating the memory space used by these variables in the method area. Pay attention to the initial value concept mentioned here, for example, a class variable is defined as:

In fact, the initial value of the variable v after the preparation stage is 0 instead of 8080, and the put static instruction that assigns v to 8080 is stored in the class constructor method after the program is compiled.

But note that if declared as:

public static final int v = 8080;

The ConstantValue attribute will be generated for v in the compilation stage, and the virtual machine will assign v to 8080 according to the ConstantValue attribute in the preparation stage.

analyze

The resolution phase refers to the process in which the virtual machine replaces symbolic references in the constant pool with direct references. Symbolic references are in the class file

public static int v = 8080;

In fact, the initial value of the variable v after the preparation stage is 0 instead of 8080, and the put static instruction that assigns v to 8080 is stored in the class constructor method after the program is compiled. But note that if declared as:

The ConstantValue attribute will be generated for v in the compilation stage, and the virtual machine will assign v to 8080 according to the ConstantValue attribute in the preparation stage.

analyze

The resolution phase refers to the process in which the virtual machine replaces symbolic references in the constant pool with direct references. Symbolic references are in the class file

public static final int v = 8080;

The ConstantValue attribute will be generated for v in the compilation stage, and the virtual machine will assign v to 8080 according to the ConstantValue attribute in the preparation stage.

analyze

The resolution phase refers to the process in which the virtual machine replaces symbolic references in the constant pool with direct references. The symbol reference is in the class file:

(1) CONSTANT_Class_info

(2)CONSTANT_Field_info

(3)CONSTANT_Method_info

and other types of constants.

symbol reference

Symbolic references have nothing to do with the layout of the virtual machine implementation, and the referenced targets do not necessarily have to be loaded into memory. The memory layouts of various virtual machine implementations can be different, but the symbolic references they can accept must be consistent, because the literal form of symbolic references is clearly defined in the Class file format of the Java Virtual Machine Specification.

direct quote

A direct reference can be a pointer to the target, a relative offset, or a handle that can indirectly locate the target. If there is a direct reference, the referenced target must already exist in memory.

initialization

The initialization phase is the last phase of class loading. After the previous class loading phase, except for the custom class loader in the loading phase, other operations are dominated by the JVM. In the initial stage, the Java program code defined in the class is actually executed.

class constructor

The initialization phase is the process of executing class constructor methods. The method is formed by combining the assignment operation of the class variable in the class automatically collected by the compiler and the statement in the static statement block. The virtual machine guarantees that the method of the parent class has been executed before the sub-method is executed. If there is no static variable assignment or static statement block in a class, the compiler does not need to generate the () method for this class. Note that class initialization will not be performed in the following situations:

(1) Referencing the static fields of the parent class through the subclass will only trigger the initialization of the parent class, but not the initialization of the subclass.

(2) Defining an array of objects will not trigger the initialization of this class.

(3) The constants will be stored in the constant pool of the calling class during compilation. In essence, there is no direct reference to the class that defines the constant, and it will not trigger the class where the constant is defined.

(4) Obtaining the Class object through the class name will not trigger the initialization of the class.

(5) When loading the specified class through Class.forName, if the specified parameter initialize is false, the class initialization will not be triggered. In fact, this parameter tells the virtual machine whether to initialize the class.

(6) Through the default loadClass method of ClassLoader, the initialization action will not be triggered.

52. Class loader

The virtual machine design team implements the loading action outside the JVM so that the application can decide how to obtain the required classes. The JVM provides three types of loaders:

Bootstrap ClassLoader

Responsible for loading classes in the JAVA_HOME\lib directory, or in the path specified by the -Xbootclasspath parameter, and recognized by the virtual machine (identified by file name, such as rt.jar).

Extension ClassLoader

Responsible for loading the class library in the JAVA_HOME\lib\ext directory, or in the path specified by the java.ext.dirs system variable.

Application ClassLoader:

Responsible for loading class libraries on the user path (classpath). The JVM loads classes through the parent delegation model. Of course, we can also implement a custom class loader by inheriting java.lang.ClassLoader.

53. Parental delegation

When a class receives a class loading request, it will not try to load the class itself first, but delegate the request to the parent class to complete. This is the case for every hierarchical class loader, so all loading requests should be sent When starting class loading, only when the parent class loader reports that it cannot complete the request (the class to be loaded is not found in its loading path), the child class loader will try to load it by itself.

One advantage of using parental delegation is that, for example, when loading the class java.lang.Object located in the rt.jar package, no matter which loader loads this class, it will eventually be entrusted to the top-level startup class loader for loading, which ensures that Using different class loaders ends up getting the same Object object

54. OSGI (Dynamic Model System)

OSGi (Open Service Gateway Initiative) is a Java-oriented dynamic model system and a series of specifications for Java's dynamic modular system.

55. Dynamically change the structure

The OSGi service platform provides the ability to dynamically change configurations on various network devices without rebooting. To minimize coupling and make these couplings manageable, OSGi technology provides a service-oriented architecture that enables these components to discover each other dynamically.

56. Modular programming and hot swap

OSGi aims to provide the basic conditions for modular programming of Java programs. OSGi-based programs are likely to be able to implement module-level hot-swapping functions. When the program is updated, only part of the program can be disabled, reinstalled, and started. , which is a very attractive feature for enterprise program development.

OSGi describes a very good modular development goal, and defines the required services and architecture to achieve this goal, and also has a mature framework for implementation support. But not all applications are suitable for using OSGi as an infrastructure. While it provides powerful functions, it also introduces additional complexity because it does not abide by the parent delegation model of class loading.

57. JVM memory model

Thread exclusive: stack, native method stack, program counter

Thread sharing: heap, method area

58. stack

Also known as the method stack, private to the thread, the thread execution method will create a stack array to store information such as the local variable table, the operation stack, the dynamic link, the method exit, etc. When the method is called, it is executed on the stack, and the method returns to the stack. .

59. Native method stack

Similar to the stack, it is also used to save the information of the execution method. The execution of the Java method uses the stack, and the native method stack is used when the Native method is executed.

60. Program counter

It saves the bytecode position executed by the current thread. Each thread has an independent counter when it works, and it only serves to execute the Java method. When the Native method is executed, the program counter is empty.

61. Heap

The largest piece of JVM memory management is shared by threads. The purpose is to store object instances. Almost all desired object instances will be placed here. When there is no available space in the heap, an OOM exception will be thrown. Depending on the life cycle of the object, The JVM manages objects in generations, and the garbage collector performs garbage collection management

62. Method area

Also known as the non-heap area, it is used to store data such as class information, constants, static variables, and code optimized by the real-time compiler that have been loaded by the virtual machine. The permanent generation of 1.7 and the metaspace of 1.8 are both an implementation of the method area .

63. Generational recycling

Generational recycling is based on two facts: most objects will not be used soon, and some objects will not be useless immediately, but they will not last for a long time

young generation->mark-copy

Old Generation -> Mark-Clear

64. The difference between heap and stack

The stack is a runtime unit, representing logic, containing basic data types and object references in the heap, and the area is continuous without fragmentation; the heap is a storage unit, representing data, which can be shared by multiple stacks (including basic data types in members , references and reference objects), the area where they are located is discontinuous and there will be fragments.

(1) Different functions

Stack memory is used to store local variables and method calls, while heap memory is used to store objects in Java. Whether it is member variables, local variables, or class variables, the objects they point to are stored in heap memory.

(2) Different sharing

Stack memory is thread private.

Heap memory is shared by all threads.

(3) Abnormal errors are different

If the stack memory or heap memory is insufficient, an exception will be thrown.

Insufficient stack space: java.lang.StackOverFlowError.

Insufficient heap space: java.lang.OutOfMemoryError.

(4) Space size

The size of the stack is much smaller than that of the heap

65. When will FullGC be triggered?

In addition to directly calling System.gc, there are four situations that trigger the execution of Full GC as follows.

(1) Insufficient space in the old generation

The old generation space will be insufficient only when the new generation objects are transferred and created as large objects and large arrays. When the space is still insufficient after executing Full GC, the following error will be thrown

error:

java.lang.OutOfMemoryError: Java heap space

In order to avoid the FullGC caused by the above two situations, when tuning, try to let the object be recycled in the Minor GC phase, let the object survive for a longer period of time in the new generation, and do not create too large objects and arrays.

(2) Permanet Generation space is full

PermanetGeneration stores some class information, etc. When there are many classes to be loaded, reflected classes, and methods to call in the system, Permanet Generation may be full. If it is not configured to use CMS GC, it will execute Full GC. If it still cannot be recycled after Full GC, the JVM will throw the following error message:

java.lang.OutOfMemoryError: PermGen space

In order to avoid the Full GC phenomenon caused by the full Perm Gen, the available methods are to increase the Perm Gen space or switch to CMS GC.

(3) Promotion failed and concurrent mode failure appear during CMS GC

For programs that use CMS for old generation GC, pay special attention to whether there are promotion failed and concurrent mode failure in the GC log. When these two conditions occur, Full GC may be triggered.

Promotionfailed is caused by the fact that the survivor space cannot be placed during Minor GC, and objects can only be placed in the old generation, and at this time the old generation cannot be placed; concurrent mode failure is caused by objects to be placed in the process of executing CMS GC at the same time The old generation, and at this time the old generation is caused by insufficient space.

The countermeasures are: increase survivorspace, old generation space or reduce the ratio of triggering concurrent GC. However, in JDK 5.0+ and 6.0+ versions, it is possible that the CMS will trigger the sweeping action long after the remark is completed due to JDK bug29 . For this situation, it can be avoided by setting -XX:CMSMaxAbortablePrecleanTime=5 (in ms).

(4) The average size of the Minor GC promoted to the Old Generation is greater than the remaining space of the Old Generation

This is a relatively complicated trigger situation. In order to avoid the phenomenon of insufficient space in the old generation caused by the promotion of new generation objects to the old generation, Hotspot made a judgment when performing Minor GC. If the Minor GC promotion obtained from the previous statistics If the average size of the old generation is greater than the remaining space of the old generation, Full GC is directly triggered.

For example, after the program triggers MinorGC for the first time, 6MB objects are promoted to the old generation, then when the next Minor GC occurs, first check whether the remaining space of the old generation is greater than 6MB, and if it is less than 6MB, execute Full GC.

When the new generation adopts PSGC, the method is slightly different. PS GC will also check after Minor GC. For example, after the first Minor GC in the above example, PS GC will check whether the remaining space of the old generation is greater than 6MB at this time. , if it is less than, it will trigger the recycling of the old generation. In addition to the above 4 situations, for Sun JDK applications that use RMI for RPC or management, by default, Full GC will be performed once an hour. You can set the interval of Full GC execution by passing -java-Dsun.rmi.dgc.client.gcInterval=3600000 at startup or by passing -XX:+ DisableExplicitGC to prohibit RMI from calling System.gc

66. What is a Java virtual machine? Why is Java called a "platform-independent programming language"?

The Java virtual machine is a virtual machine process that can execute Java bytecode. Java source files are compiled into bytecode files that can be executed by the Java virtual machine. Java was designed to allow applications to run on any platform without requiring programmers to rewrite or recompile for each platform individually. The Java virtual machine makes this possible because it knows the instruction length and other characteristics of the underlying hardware platform.

67. Object allocation rules

(1) Objects are allocated in the Eden area first. If there is not enough space in the Eden area, the virtual machine executes a Minor GC.

(2) Large objects directly enter the old age (large objects refer to objects that require a large amount of continuous memory space). The purpose of this is to avoid a large number of memory copies between the Eden area and the two Survivor areas (the new generation uses the copy algorithm to collect memory).

(3) Long-lived objects enter the old age. The virtual machine defines an age counter for each object. If the object has gone through Minor GC once, the object will enter the Survivor area. After that, the age of the object will increase by 1 every time it passes through Minor GC. Until the threshold is reached, the object will enter the old age area.

(4) Dynamically judge the age of the object. If the sum of the sizes of all objects of the same age in the Survivor area is greater than half of the Survivor space, objects whose age is greater than or equal to this age can directly enter the old age.

(5) Space allocation guarantee. Every time a Minor GC is performed, the JVM will calculate the average size of the objects moved from the Survivor area to the old area. If this value is greater than the size of the remaining value in the old area, a Full GC will be performed. If it is less than the value, check the HandlePromotionFailure setting. If it is true, only Monitor will be performed. GC, if false, perform Full GC

68. Describe the principle mechanism of JVM loading class files?

The loading of classes in the JVM is implemented by the class loader (ClassLoader) and its subclasses. The class loader in Java is an important Java runtime system component that is responsible for finding and loading class files at runtime. the type.

Due to the cross-platform nature of Java, the compiled Java source program is not an executable program, but one or more class files. When a Java program needs to use a certain class, the JVM will ensure that the class has been loaded, connected (validated, prepared, and parsed) and initialized.

Class loading refers to reading the data in the .class file of the class into memory, usually by creating a byte array and reading it into the .class file, and then generating a Class object corresponding to the loaded class. After the loading is complete, the Class object is not complete, so the class at this time is not yet available.

When the class is loaded, it enters the connection phase, which includes three steps: verification, preparation (allocating memory for static variables and setting default initial values) and resolution (replacing symbolic references with direct references). Finally, the JVM initializes the class,

include:

(1) If the class has a direct parent class and the class has not been initialized, then initialize the parent class first;

(2) If there are initialization statements in the class, execute these initialization statements in sequence. Class loading is done by class loaders, which include: root loader (BootStrap), extension loader (Extension), system loader (System) and user-defined class loader (java.lang.ClassLoader's Subclass).

Starting from Java 2 (JDK 1.2), the class loading process adopts the parent delegation mechanism (PDM). PDM better guarantees the security of the Java platform. In this mechanism, the Bootstrap that comes with the JVM is the root loader, and other loaders have and only have one parent class loader. The loading of the class first requests the parent class loader to load, and when the parent class loader is helpless, its child class loader will load it by itself. The JVM does not provide references to Bootstrap to Java programs. The following is a description of several class loaders

Bootstrap: generally implemented with local code, responsible for loading the JVM basic core class library (rt.jar);

Extension: Load the class library from the directory specified by the java.ext.dirs system property, and its parent loader is Bootstrap;

System: Also known as the application class loader, its parent class is Extension. It is the most widely used class loader. It records classes from the directory specified by the environment variable classpath or the system property java.class.path, and is the default parent loader for user-defined loaders.

69. Java object creation process

(1) When the JVM encounters an instruction to create a new object, it first checks whether the parameters of this instruction can define a symbolic reference to a class in the constant pool. Then load this class (the class loading process will be discussed later)

(2) Allocate memory for the object. One method "pointer collision", one method "free list", and finally the commonly used method "local thread buffer allocation (TLAB)"

(3) Initialize the object memory space except the object header to 0

(4) Make necessary settings for the object header

70. Briefly describe the object structure of Java

A Java object consists of three parts: object header, instance data, and alignment padding.

The object header consists of two parts. The first part stores the runtime data of the object itself: hash code, GC generation age, lock identification status, lock held by the thread, and biased thread ID (generally occupying 32/64 bits). The second part is the pointer type, which points to the class metadata type of the object (ie which class the object represents). If it is an array object, another part of the object header is used to record the length of the array.

Instance data is used to store the real effective information of the object (including inherited from the parent class and defined by itself)

Alignment filling: JVM requires that the starting address of the object must be an integer multiple of 8 bytes (8-byte alignment)

71. How to judge whether an object can be recycled

There are generally two ways to determine whether an object is alive:

Reference counting: Each object has a reference counting attribute. When a reference is added, the count is incremented by 1, and when the reference is released, the count is decremented by 1. When the count is 0, it can be recycled. This method is simple and cannot solve the problem of circular references between objects.

Reachability Analysis: Starting from GC Roots to search downwards, the path traveled by the search is called the reference chain. When an object does not have any reference chain connected to GC Roots, it proves that the object is unavailable and unreachable.

72. Will garbage collection occur in the permanent generation of the JVM?

Garbage collection does not happen in the permanent generation. If the permanent generation is full or exceeds a threshold, a full garbage collection (Full GC) will be triggered. If you look carefully at the output of the garbage collector, you will find that the permanent generation is also collected. This is why correct permanent generation size is very important to avoid Full GC. Please refer to Java8: From the permanent generation to the metadata area (Note: Java8 has removed the permanent generation, and added a new native memory area called the metadata area)

73. Garbage collection algorithm

There are three basic algorithms for GC: mark-sweep algorithm, copy algorithm, and mark-compression algorithm. Our commonly used garbage collectors generally use generational collection algorithms.

mark-sweep algorithm

The "Mark-Sweep" algorithm, like its name, is divided into two stages: "Mark" and "Sweep". tagged object.

copy algorithm

"Copying" collection algorithm, which divides the available memory into two pieces of equal size according to capacity, and only uses one of them at a time. When the memory of this block is used up, copy the surviving object to another block, and then clean up the used memory space at one time.

mark-compression algorithm

The marking process is still the same as the "mark-clear" algorithm, but the subsequent steps do not directly clean up recyclable objects, but let all surviving objects move to one end, and then directly clean up the memory outside the end boundary

Generational Collection Algorithm

The "Generational Collection" algorithm divides the Java heap into the new generation and the old generation, so that the most appropriate collection algorithm can be adopted according to the characteristics of each age

Tuning related

74. What are the tuning commands?

Sun JDK monitoring and fault handling commands include jps jstat jmap jhat jstack jinfo

(1) jps, JVM Process Status Tool, displays all HotSpot virtual machine processes in the specified system.

(1) jstat, JVM statistics Monitoring is a command used to monitor the status information of the virtual machine when it is running. It can display the running data such as class loading, memory, garbage collection, and JIT compilation in the virtual machine process.

(3) jmap, the JVM Memory Map command is used to generate heap dump files

(4) jhat, the JVM Heap Analysis Tool command is used in conjunction with jmap to analyze the dump generated by jmap. jhat has a built-in miniature HTTP/HTML server. After generating the dump analysis results, you can view them in the browser

(5) jstack, used to generate a thread snapshot of the java virtual machine at the current moment.

(6) jinfo, JVM Configuration info This command is used to view and adjust the operating parameters of the virtual machine in real time

75. Tuning tools

Commonly used tuning tools are divided into two categories, jdk comes with monitoring tools: jconsole and jvisualvm, and third parties include: MAT (Memory Analyzer Tool), GChisto.

(1) jconsole, Java Monitoring and Management Console is a java monitoring and management console that comes with the JDK starting from java5, and is used to monitor memory, threads and classes in the JVM

(2) jvisualvm, jdk comes with a versatile tool that can analyze memory snapshots and thread snapshots; monitor memory changes, GC changes, etc.

(3) MAT, Memory Analyzer Tool, an Eclipse-based memory analysis tool, is a fast, feature-rich Javaheap analysis tool, which can help us find memory leaks and reduce memory consumption

(4) GChisto, a professional tool for analyzing gc logs

76. When do Minor GC and Full GC occur respectively?

MGC, also called YGC, occurs when the memory of the new generation is insufficient, and FGC occurs when the memory of the JVM is insufficient.

77. What JVM performance tuning do you know

Set the heap memory size

-Xmx: Maximum heap memory limit.

Set the young generation size. The new generation should not be too small, otherwise a large number of objects will flood into the old generation

-XX:NewSize: new generation size

-XX:NewRatio The proportion of the new generation and the old generation

-XX:SurvivorRatio: the ratio of Eden space and survivor space

Set garbage collector young generation -XX:+UseParNewGC old generation -XX:+UseConcMarkSweepGC

Guess you like

Origin blog.csdn.net/Design407/article/details/107109757