Preface:

Recently, I often received private messages from my friends asking me if I could help to sort out a list of INTERVIEW questions related to JVM. They said that when I was in a big factory, I asked a lot of questions about this topic, and I failed to learn the key points every time I learned them by myself. Here he is, a detailed JVM interview for you to sort out below!

When will stack memory overflow occur?

1. The stack is thread private, and the life cycle of the stack is the same as that of the thread. When each method is executed, a stack frame will be created, which contains local variable table, operand stack, dynamic link, method exit and other information.

StackOverFlowError is raised when thread requests exceed the maximum stack depth allowed by the virtual machine.

3. Adjust the -xss parameter to adjust the JVM stack size

JVM memory model

The JVM divides the virtual machine into five areas:

Program counter, virtual machine stack, local method stack, Java heap, method area

Program counter:

Thread private, is a small memory space, as the current thread line number indicator, used to record the current VM thread instruction address.

Virtual machine stack:

A stack frame is created for each method execution to store local variables, operands, dynamic links, and method returns. A StackOverFlowError is raised when a thread requests a stack depth that exceeds the maximum allowed by the VIRTUAL machine.

Local method stack:

Thread is private and saves the information of Native method. When a thread created by JVM calls native method, THE JVM will not create stack frames for the thread in the virtual machine stack, but simply dynamically link and directly call this method.

Pile:

The Java heap is a chunk of memory shared by all threads. Almost all object instances and arrays are allocated on the heap, so garbage collection often occurs in this area.

Methods area:

Stores loaded class information, constants, static variables, and just-in-time compiler compiled code data. In JDK1.8, the method area is replaced by the metadata area. The original method area is divided into two parts. 1: loaded class information. 2: runtime constant pool. The loaded class information is stored in the metadata area, and the runtime constant pool is stored in the heap;

What does a full GC look like in a JVM? How does the target get promoted to the old age?

Java heap = New generation + old generation; Cenozoic = Eden + Suivivor (S0 + S1), the default allocation ratio is 8:1:1; When Eden’s space is full, a Minor GC is triggered to collect the garbage of the new generation. The surviving objects are allocated to the Survivor area and the large objects (objects that require a large amount of continuous memory) are allocated to the old age. If you survive a Minor GC, your age is +1. If you survive a Minor GC, your age is +1. If you survive a Minor GC, your age is +1. When the age is full and no more objects can be held, a full GC is triggered. The full GC stores the entire heap (both young and old); A Major GC is a GC that occurs in an old age, clearing an old age area, often accompanied by at least one minor GC.

Garbage collection algorithm in Java?

There are four garbage collection algorithms in Java:

Mark removal method, mark sorting method, copy algorithm, generation collection algorithm;

Mark removal method:

Step 1: Use reachability to traverse memory, marking alive objects and garbage objects;

Step 2: Iterate again and recycle all marked objects; Features: efficiency is not good, marking and cleaning efficiency is not high; After marking and clearing, a large number of discontinuous spatial fragments will be generated, which may cause the program to allocate large objects and not find continuous fragments and have to trigger a GC.

Mark finishing method:

Step 1: Use reachability to traverse memory, marking alive objects and garbage objects;

Step 2: Move all surviving objects to a segment, reclaim all objects outside the end boundary; Features: Suitable for living objects, less garbage; No space debris is generated in the process of cleaning up;

Replication algorithm:

Divide the memory into two pieces of equal size according to the size of the capacity, and use only one piece at a time. When one piece is used up, the surviving objects are moved to another piece, and then the used memory space is removed. Features: No space debris; Very low memory usage;

Generational collection algorithm:

In the new generation, a large number of objects die and a small number of objects survive. Therefore, the replication algorithm only needs to pay a small amount of the replication cost of the surviving objects to complete the collection. In the old age, because the survival rate of the object is very high, there is no extra space for him to allocate guarantee, so the use of mark cleaning or mark sorting algorithm for recycling;

How to determine whether an object is alive or not?

There are two algorithms to judge whether an object is alive or not:

1. Reference counting;

2. Accessibility analysis algorithm;

Reference counting method:

Set a reference counter for each object. When the object is referenced in one place, the reference counter is +1, and when the reference fails, the reference counter is -1. When the reference counter is 0, the object is not referenced, that is, garbage, waiting to be collected. Disadvantages: It cannot solve the problem of circular reference. When A references B and B also references A, the reference of AB object is not 0 and garbage collection cannot be performed. Therefore, mainstream VMS do not use this method.

Accessibility analysis:

Search down from an object called GC Roots. If an object is not connected to GC Roots by any reference chain, it is not available. There are several types of objects that can be used as GC Roots in Java:

Virtual machine stack reference object method area class static attribute reference variable method area constant pool reference object local method stack JNI reference object but an object that meets the above conditions, will not be immediately recycled, also need to be marked twice; First mark: Determine whether the current object has a Finalize () method and the method has not been executed. If it does not exist, mark the object as garbage and wait for recycling. If so, mark the second time; The second tag will put the current object into the F-Queue and generate a Finalize thread to execute the method. The virtual machine does not guarantee that the method will be executed, because if the thread executes slowly or enters a deadlock, the recycle system will crash. If there is no direct or indirect reference to GC Roots after finalize method is executed, the object will be reclaimed.

What kinds of garbage collectors are there and what are their advantages and disadvantages? What’s the difference between CMS and G1?

Garbage collectors fall into the following categories:

Serial, ParNew, Parallel Insane, Serial Old, Parallel Old, CMS, G1.

Serial:

A single-threaded collector must stop the world when collecting garbage, using a copy algorithm.

ParNew:

The multithreaded version of the Serial collector also needs to stop the world and copy the algorithm.

ParallelScavenge:

New generation collectors, collectors of replication algorithms, concurrent multi-threaded collectors, the goal is to achieve a controllable throughput, and ParNew’s biggest difference is the GC auto-tuning strategy; The vM collects performance monitoring information based on the system running status and dynamically sets these parameters to provide optimal pause time and maximum throughput.

Serial Old:

An older version of the Serial collector, the single-threaded collector, uses a tag collation algorithm.

The Parallel Old:

The Parallel Exploiter is an older version of the Parallel Exploiter, using a multi-threaded, mark-collation algorithm.

CMS:

Is a collector to obtain the shortest recovery pause time as the goal, mark clearing algorithm, operation process: initial mark, concurrent mark, re-mark, concurrent clear, the end of the collection will produce a large number of space debris;

G1:

The operation process mainly includes the following: initial marking, concurrent marking, final marking, screening and recycling. No space debris can be generated and the pauses can be precisely controlled; G1 divides the whole heap into multiple regions (regions) of equal size. G1 tracks the size of garbage in each Region and maintains a priority list in the background. According to the allowed collection time, the Region with the largest collection value is prioritized to achieve the highest collection efficiency within a limited time.

What is class loading?

The virtual machine loads the data describing the class into memory, verifies, parses, and initializes the data, and finally becomes a class object that can be directly used by the VIRTUAL machine.

Class loading process?

It is mainly divided into the following processes:

Load, validate, prepare, parse, initialize;

Loading: Loading is divided into three steps:

1. Obtain the binary stream of a class by its full class name;

2. Convert the static storage structure of the binary stream into the runtime data structure of the method area;

Generate a class object for the class in the heap.

Validation:

Verify that byte stream information in this class file is consistent with virtual machine requirements and does not threaten JVM security;

Preparation:

Allocates memory for static variables of class objects and initializes their initial values.

Resolution:

In this stage, symbolic reference is transformed into direct reference.

Initialization:

In the initialization phase, the Java code defined in the class is executed; The initialization phase is the process of calling the class constructor;

What is a class loader? What are the common class loaders?

Class loaders are:

Getting the binary byte stream of a class by its full class name is called a classloader;

Class loaders fall into the following four categories:

Start the classloader:

Used to load Java core libraries, cannot be directly referenced by Java programs;

Extended class loaders:

The virtual machine implementation of Java provides an extension library directory in which the classloader finds and loads Java classes.

System class loader:

It loads classes according to the Java classpath. In general, Java applications load classes through it.

Custom class loaders:

Implemented by Java language, inherited from ClassLoader;

What is the parental delegation model?

When a classloader receives a classload request, it first does not try to load the request itself. Instead, it delegates the request to the parent classloader. Only when the parent classloader fails to find the class in its search scope, the child loader will try to load the class itself.

Why parent delegation model?

To prevent multiple identical bytecodes in memory; Because without parental delegation, the user can define a java.lang.String class by himself, and there is no guarantee that the class is unique;

How to break the parental delegation model?

Custom ClassLoader, inherit ClassLoader class, rewrite loadClass method and findClass method;

Strong reference, soft application, weak reference, virtual reference difference?

Strong references:

Strong references are the most widely used references. If an object has a strong reference, the garbage collector will never collect it. When there is not enough memory, the garbage collector would rather throw OutofMemoryErrors than collect objects with strong references. We can reclaim a strongly referenced object by explicitly setting it to NULL and making the GC think there is no reference to the object.

Soft references:

A soft application is a description of useful but unnecessary objects (SoftReference in Java). An object is discarded only when the memory is insufficient. A soft reference can be used in conjunction with a reference queue. If the object referenced by the soft reference is collected by the garbage collector, the virtual machine adds the soft reference to the corresponding reference queue.

Weak references:

WeakReference is used to describe some unnecessary objects, which is represented by WeakReference in Java. In garbage collection, once an object is found to have only soft reference, the object will be reclaimed no matter whether the current memory space is sufficient. A weak reference can be used in conjunction with a reference queue. If the object referenced by a weak reference is garbage collected, the virtual machine adds the reference to the object to the reference queue associated with it.

Phantom reference:

A virtual reference is a kind of reference that cannot be used to represent the life cycle of an object and can be reclaimed at any time. A virtual reference is mainly used to track the activities of an object being garbage collected. The difference between a virtual reference and a soft reference and a weak reference is that a virtual reference must be used together with a reference queue. During garbage collection, if an object is found to have only virtual references, the reference of the object will be added to the reference queue associated with it. The program can know whether the referenced object needs to be garbage collected by discovering whether virtual references have been added to the reference queue.

The last

I have [free] Java architecture learning materials, learning technology content includes: Spring, Dubbo, MyBatis, RPC, source code analysis, high concurrency, high performance, distributed, performance optimization, micro services advanced architecture development and so on.

Also, Java core knowledge points + a full set of architect learning materials and video + a major factory interview treasure book + interview resume template can be received + Ali Meituannetease Tencent Xiaomi IQiyi Quick hand bilibilii interview questions all for you!

Welcome to join the Java architecture learning exchange: 736398039 code: J J