Learning how to tune JVM is very important for Java engineers, whether it is a problem encountered in the actual project, or in the interview, all need this piece of knowledge, small make up by simple into deep, to share a wave.

1.JDK, JRE, and JVM?

Java Development Kit (Jdk) : software Development package of the Java language. Includes the Java runtime environment Jre.

Java Runtime Environment (Jre) : A Java Runtime Environment, including the Jvm.

Jvm (Java Virtual Machine) :

  • A specification for computer equipment.
  • The Java language does not need to be recompiled when running on different platforms. The Java language uses the Java Virtual machine to mask platform-specific information, allowing Java language compilers to run unmodified on multiple platforms by generating object code (bytecode) that runs on the Java Virtual machine.

The Jdk includes the Jre and the Jre includes the JVM.

2. How does the launcher see which classes are loaded, and in what order?

Java -xx :+TraceClassLoading Concrete class

Java-verbose concrete class

3. What are the 10 main components of a class bytecode file?

  • MagicNumber
  • Version
  • Constant_pool
  • Access_flag
  • This_class
  • Super_class
  • Interfaces
  • Fields
  • Methods
  • Attributes

4. Draw the JVM memory structure map.

5. Program counter

Thread private memory. It occupies a very small space and acts as a line number indicator of the bytecode being executed by the current thread. The bytecode interpreter works by changing the value of this counter to select the bytecode of the next instruction to be executed. Branch, loop, jump, exception handling, thread recovery and other basic functions depend on this counter to complete.

6.Java virtual machine stack

Thread private memory. It has the same life cycle as a thread, and the virtual stack describes an in-memory model of Java method execution; When each method is executed, a stack frame is created to store local variables, action stacks, dynamic links, method exit information, and so on. Each method is called until the execution is complete, corresponding to a stack frame in the virtual machine from the stack to the stack process.

7. Local method stack

The role of the local method stack is very similar to that of the virtual machine stack, except that the virtual machine stack performs Java method services for the virtual machine, while the local stack uses Native method services for the virtual machine.

8. Java heap

It is the largest chunk of memory managed by the Java virtual machine. The Java heap is an area of memory shared by all threads and created when the virtual machine is started. The sole purpose of this memory area is to hold object instances, and almost all object instances are allocated memory here.

However, as JIT compilers evolve and escape analysis matures, on-stack allocation, light-and-replace optimization techniques will allow some subtle changes to occur, making it less absolute that all objects are allocated on the heap.

9. The method of area

Is an area of memory shared by threads that stores data such as class information that has been loaded by the virtual machine, constants, static variables, code compiled by the just-in-time compiler, etc.

10. Runtime constant pool?

The Constant PoolTable is used to store the literal and symbolic references generated at compile time. The Constant PoolTable is used to store the Constant references generated at compile time in the method area after the Class is loaded.

11. When to throw StackOverflowError?

If the stack depth requested by the thread is greater than the depth allowed by the virtual machine, a StackOverflowError is raised.

12. What is the difference between Java7 and Java8 in the memory model?

Java8 eliminates persistent generation and replaces it with Metaspace, which is stored in Native memory.

13. What are the two memory areas that programmers care about most?

Heap and Stack, generally we will divide Java memory into Heap and Stack memory, this is a relatively crude division, but in reality, Java memory area is very complex.

14. What is direct memory?

Direct memory is not part of the virtual machine’s run-time data region, nor is it defined in the Java Virtual Machine specification, but it is frequently used and is subject to OutofMemoryErrors.

The NIO (New Input/Output) class has been added to JDK1.4, introducing a channe-based and buffer-based I/O approach. It is also possible to use Native libraries to allocate out-of-heap memory directly, and then operate as a reference to that memory via a DirectByteBuffer object stored in the Java heap.

15. Outofmemoryerrors occur in all run-time areas of VIRTUAL machine memory except in which area?

Program counter.

16. When can a heap overflow occur?

Heap memory stores object instances. We just keep creating objects. And make sure that gc roots have a reachable path between the objects to prevent the garbage collection mechanism from cleaning these objects. The number of objects reaches its maximum. Memory overflow exception occurred after the heap capacity was limited.

17. How to implement a heap overflow?

public class Cat {

    public static void main(String[] args) {
        List list = new ArrayList();
        while (true) {
           list.add(newCat()); }}}Copy the code

18. When does a space throw an OutOfMemoryError?

An OutOfMemoryError is thrown if the virtual machine cannot allocate enough memory while extending the stack.

19. How to implement StrackOverflowError?

 public static void main(String[] args) {
     eat();
 }

 public static void eat (a) {
     eat();
 }
Copy the code

20. How do I set the direct memory capacity?

Specified by -xx :MaxDirectMemorySize. If not specified, it defaults to the maximum value of the Java heap.

21.Java heap memory composition?

Heap size = New generation + old age. Java8 does not have Permanent Generation.

Among them, Young is divided into Eden, S0 (from) and S1(to).

22. What is the default Edem ratio?

Edem : from : to = 8 : 1 : 1

This ratio can be set by -xx :SurvivorRatio

23. Garbage marking stage?

Before the GC performs garbage collection, the GC performs garbage collection only when the object is marked as dead, in order to distinguish whether the object is alive or not. This process is known as the garbage marking phase.

24. Reference counting?

For object A, as long as any object references A, the reference counter of A is increased by 1. When the reference is invalid, the reference counter is decreased by 1. When the counter is 0, it can be reclaimed.

But it doesn’t solve the problem of circular references.

25. Root search algorithm?

The following search algorithm searches whether the target object connected by the root object set is reachable from top to bottom (after using the root search algorithm, the living object in memory will be directly or indirectly connected by the root object set). If the target object is unreachable, it means that the object has died. You can Mark it as a garbage object in instanceOopDesc’s Mark World.

In the root search algorithm, only objects that can be connected directly or indirectly by the root object set are viable objects.

26. Three common garbage collection algorithms in the JVM?

Mark_Sweep algorithm

Copying algorithms

Mark-compact algorithm

27. Mark-erase algorithm?

All marked objects to be recycled are marked first, and all marked objects are recycled after the marking is completed.

Disadvantages:

  • Labeling and scavenging are inefficient.
  • Space problems after clearing produce a large number of discontinuous memory casually. If you have large objects, you run out of space and have to trigger another garbage collection action ahead of time.

28. Copy algorithm?

He divides the available memory into two equally sized pieces by capacity, uses one piece at a time, and when this piece is used up, copies the remaining objects onto the other piece, and then cleans up the used memory space at a time.

Advantages:

Memory fragmentation is resolved.

Disadvantages:

Shrink the original memory by half, the more live objects, the less efficient.

29. Mark-decluttering algorithm?

Mark the objects to be reclaimed, move all surviving objects to one end, and then clean up the memory directly beyond the boundary. The problems of copy algorithm and mark cleaning algorithm are solved.

30. Generational collection algorithm?

The current garbage collection of commercial virtual machines is based on the “generational mobile algorithm”, which divides the memory into several blocks based on the lifetime of the object, usually old and new. Use the most appropriate collection algorithm according to the characteristics of each generation.

31. Garbage collector?

If the garbage collection algorithm is the methodology, the garbage collector is the implementation. The wired symbol can be used together.

32.Stop The World?

To do garbage collection, you must suspend all other worker threads, something Sun calls “Stop The World.”

33.Serial collector?

Single-threaded collector, single-threaded in the sense that it stops the world. Garbage collection needs to stop the world until it is collected. So the collector experience is poor.

34.PartNew collector?

The multithreaded version of the Serial collector behaves almost the same as Serial, except that it uses parallel collection to reclaim memory.

You can manually specify the use of the ParNew collector to perform memory reclamation with the option “-xx :+UseParNewGC”.

36.Parallel Scavenge?

Is a new generation collector, a collector for copying algorithms, and a multithreaded parallel collector. Unlike PartNew, it focuses on achieving a manageable throughput (Thoughput) for a program. That is, throughput = run user code time /(run user code time + garbage collection time)), high throughput can make the most efficient use of CPU time, as soon as possible to complete the program’s computing tasks, mainly suitable for the background operations without too much interaction.

It can accurately control throughput with 2 parameters and make more efficient use of CPU.

-xx :MaxCcPauseMillis and -xx :GCTimeRatio

37.Parallel Old collector?

An older version of the Parallel Avenge collector, which uses multithreading and mark-collation algorithms. It’s only available in JDK 1.6.

38.CMS collector?

The Concurrent Mar Sweep collector is a collector whose goal is to obtain the shortest collection pause time. Pay attention to the response speed of the service, and expect the system to stop for the shortest time. A mark-sweep algorithm is used for garbage collection.

39.CMS garbage collection steps?

  1. Initial tag (Stop the World)

  2. Concurrent tags

  3. Re-mark (Stop the World)

  4. Concurrent remove

    The initial tag simply marks objects that GC Roots can be directly associated with, which is fast.

    Concurrent markup is the process of Gc Roots Tracing.

    Re-marking is to correct the mark record of the part of the object whose mark changes because the user program continues to run during concurrent marking. The pause time at this stage is generally longer than the initial mark time, but much shorter than the concurrent mark time.

    Concurrent tagging takes the longest, but can work with the user thread at this point.

41.CMS collector advantages? Weaknesses?

Advantages:

Concurrent collection, low pause

Disadvantages:

  • Very sensitive to CPU resources.
  • Unable to handle floating garbage.
  • Memory fragmentation problem.

42.G1 collector?

The Garbage First collector is the latest development in current collector technology. The G1 collector is provided in JDK 1.6_UPDATe14.

The G1 collector is based on the mark-collation algorithm, which avoids the problem of memory fragmentation.

Pause times can be controlled so precisely that the user explicitly specifies that no more than N milliseconds are spent in garbage collection within a time segment of M milliseconds, which is almost characteristic of the real-time Java (RTSJ) garbage collector.

42. How does the G1 collector improve collection methods?

Region-wide garbage collection was avoided, as previous collectors tended to cover the entire new generation or the old generation. G1 divides the entire Java heap (including the new generation and the old generation) into multiple independent regions of fixed size, tracks the degree of garbage accumulation in these regions, maintains a priority Lipio, and gives priority to the areas with the most garbage collection according to the allowed collection time each time. In order to achieve higher efficiency.

43. Virtual machine process status tool?

JPS (Jvm Process Status Tool), its function is similar to PS.

You can list running VIRTUAL machine processes and display the name of the executing Main Class (Main Class, the Class where the Main () function is located), as well as the unique ID of the local VIRTUAL machine of the Zhejiang process.

JPS [options] [hostid]

-q Main output LVMID, omitting the name of the main class

-m Prints the parameters passed to the main() function of the main class when the virtual machine process starts

-l Displays the full name of the main class and the Jar path if the process execution is a Jar package

-v Displays JVM parameters for starting a VM process

Virtual machine statistics tool?

Jstat (JVM Statistics monmotortool) is a command line motoring Tool for monitoring the various running status of a VIRTUAL machine. It can display classloading, memory, garbage collection, JIT compilation, and other running data in local or remote virtual machine processes.

jstat [option vmid [interval[s|ms] [count]] ]

Interval Query interval

Count Number of queries

If these two parameters are not used, the query is performed once by default.

Option indicates the VM information that the user wants to query. The options are classified into three types:

  • Class loading
  • Garbage collection
  • Runtime compile status

45. What are the main options of jstat?

-class Monitors the number of class loads, unloads, total space, and time consumed by class load locks

– GC monitors Java heap health, including Eden zone, 2 survivor zones, old age

-gcCapacity monitors much the same as -GC, but the output focuses on the maximum and minimum space used by various regions of the Java heap

-gCUTIL monitors basically the same as -GC, focusing on the percentage of space that has been used

-gCCause has the same function as -gcutil, but outputs the extra cause of the previous GC

– GcNew monitors the status of new generation GC

-gcnewCapacity Monitors the same content as -gcnew. The output focuses on the maximum and minimum space used

-gcold monitors GC in old age

-gcoldCapacity Monitors the same content as -gcold, focusing on the maximum and minimum space used

– Compiler Displays the compiled methods and time used by the JIT compiler

45. Configure the information tool?

The Configuration Info for Java (JINFO) function allows you to view and adjust vm parameters in real time.

Using the -v parameter of the JPS command, you can view the specified parameter list when the VM starts.

Jinfo syntax: jinfo [option] pid

46. Memory mapping tools?

The jmap(Memory Map for Java) command is used to generate heapdump snapshots (commonly known as heapdump or dump files).

Syntax: jmap [option] vmID

It can also query finalize execution queues, Java heap and persistent generation details, if space usage, which collector is currently in use, etc.

  • -dump Generates a snapshot of the Java heap dump. Live indicates whether only the live objects are dumped
  • – finalizerInfo Displays objects in the F-queue that are waiting for the Finalizer thread to execute the Finalize method. This works only on Linux/Solaris
  • -heap Displays Java heap details, such as which collector is used, parameter configuration, and generation status.
  • -histo Displays statistics about objects in the heap, including classes, number of instances, and total capacity.
  • -f If the VM process does not respond to the -dump option, you can use this option to forcibly generate a dump snapshot.

Vm heap-to-Storage snapshot analysis tool?

Jhat (JVM Heap Analysis Tool) is used to analyze Heap dump snapshots generated by JMAP.

Stack trace tool?

The jstack(Stack Trace for Java) command is used to generate a snapshot (thread dump or Javacore file) of a VM at the current time. A thread snapshot is a stack of methods being executed by each thread in the current VIRTUAL machine. The main purpose of a thread snapshot is to locate the cause of a long pause in a thread.

jstack [option] vmid

-f Forces the thread stack to be outputted when a normally outputted request is not answered

-l Displays additional information about the lock in addition to the stack

-m Displays the C/C++ stack if the local method’s flower is called

49. Besides the command line, what other visualization tools are there?

JConsole and VisualVM, two tools that are official members of the JDK.

50. Life cycle of a class?

Outside the chain picture archiving failure, the source station might be hotlinking prevention mechanism, proposed to directly upload picture preserved (img – ew2YLY4D – 1589364369210) (/ Users/qianliying/Library/Application Support/typora-user-images/image-20200507122940774.png)]

51. Class loading process?

Load -> Verify -> Prepare -> Parse -> initialize

52. How many steps are there in the linking stage?

Verify -> Prepare -> Parse

53. In what five cases must a class be initialized?

1. When encountering the four bytecode instructions of New, getstatic, putstatic and Invokestatic.

2. Reflection calls to classes using methods of the java.lang.relect package.

3. When initializing a class, initialize the parent class first if the parent class is not initialized.

4. When the virtual machine starts, the primary class (the class that executes the main() method) is specified, and the primary class needs to be initialized first.

5. JDK1.7 dynamic language support, if a Java lang. Invoke. Analytical results REF_getStatic MethodHandle example finally, REF_putStatic, REF_invokeStatic method handles, If the class corresponding to the handle is not initialized, initialize the class first.

54. Will the following code output?

public class TestStatic {

    public static void main(String[] args) { System.out.println(SubClass.value); }}class SuperClass {
    static {
        System.out.println("Java super init");
    }

    public static int value = 123;
}

class SubClass extends SuperClass {

    static {
        System.out.println("Java sub init"); }}Copy the code

Output:

Java small cafesuper init
123
Copy the code

Reason: For static fields, only the class that directly defines the field is initialized.

55. What does the load phase do?

Gets a byte stream in binary Classfile format based on a known class fully qualified name.

Transform the static storage structure represented by this byte stream into the runtime data structure of the method area.

Generate a java.lang.Class object in memory that represents the Class and acts as an access point for the Class’s various data in the method area.

56. What is the significance of the verification phase?

Ensure that the byte stream in the Class file meets vm requirements and does not compromise VM security. When a byte stream nonconforming to the specification is detected, the corresponding exception is thrown.

57. What are the stages of verification?

  • File format validation
  • Metadata validation
  • Bytecode verification
  • Symbolic reference verification

58. Preparation?

This stage formally allocates memory for class variables and sets their initial values. It is important to note that class variables are defined as static, not instance variables.

59. How are final class variables attached in the preparation phase?

public static final int value = 2333;

The number 2333 is attached.

60. The parsing phase?

This stage is the process by which the virtual machine replaces symbolic references in the constant pool with direct references.

61. Initialization?

The stage in which a class or class performs an initialization method and a class variable is actually attached.

62. What are class loaders?

  • Start the class loader (BootstrapClassLoader)
  • Extended class loader (ExtClassLoader)
  • Application Classloader

63. BootstrapClassLoader?

Bootstrap ClassLoader: the Bootstrap ClassLoader is responsible for loading Java core classes. It is implemented in native C++ code and does not inherit from java.lang.ClassLoader.

Responsible for loading the following three types of core libraries:

% JAVA_HOME % / jre/lib directory.

-Xbootclasspath Specifies the directory.

System property Sun.boot.class. path Specifies a jar package with a specific name in the directory specified by the system property.

64. ExtClassLoader?

Extension ClassLoader: is responsible for loading Extension classes.

Loads the specified class library in either of the following cases:

  • % JAVA_HOME % / jre/lib/ext directory
  • Java.ext.dirs specifies all the class libraries in the directory

65. AppClassLoader?

App ClassLoader: Is responsible for loading application class libraries.

Load the following two specified class libraries:

  • Java command -classpath, -cp options
  • The system property java.class.path specifies the JAR package and classpath

66. Can I customize class loaders?

Yes, the custom loader has App ClassLoader as its parent class.

67. Parental delegation mechanism?

When you have a class that needs to be loaded, you go up the hierarchy, like a custom class loader, and you ask your parent class loader, AppClassLoader, AppClassLoader asked ExtClassLoader ExtClassLoader asked BootstrapClassLoader, such as start classes have been loaded the class, other loader is not loaded. If the parent class loader fails to load, the subclass will try to load. If all loads fail to load the class, throw ClassNotFountException.

68. How do I check which classes are loaded, in what order?

java -XX:+TraceClassLoading com.xiaoka.HelloFriend

PS: Share every week. Public account [Java Xiaocaxiu] background reply “999” to receive Java full level engineering lion interview manual. PDF. The new man asks for three.