2019 JVM interview were asked what? Quick look at this 22 interview questions! (With answers parsing)

A. Java class loading process?

Java class loading process to go through about 7:

1. Load

Load is the first class loading process, at this stage, to be completed about three things:
• Get the class of binary stream by the fully qualified name of a class.
• The static storage structure is converted into a binary stream data structure to the runtime method.
• generating a Class object class in memory, such as data access to the inlet.

2. Verify

The purpose of verification is to ensure that the information in the file byte stream Class of harm to the virtual machine does not return to complete the following four main bell verify at this stage:
• File format validation: validation of a byte stream for compliance with Class files, such as major and minor version numbers are within the scope of the current virtual machine, whether there is a constant in the constant pool type is not supported.
• metadata validation: the information described bytecode semantic analysis, such as whether the class has a parent class, whether or not integrated inherited the like.
• bytecode verification: the entire verification process is the most complex stage, by analyzing the validation data flow and control flow of the program to determine whether the correct semantics, the main body for the authentication method. The: method of the correct type conversion, like the jump instruction is correct.
• verification of symbolic references: the action takes place behind the resolution process, primarily to ensure that the analysis operation is performed properly.

3. Prepare

Preparation phase is allocated memory and initialized to default values ​​for the static variable class, which will be allocated in the memory area method. Preparation stage memory not allocated class instance variables, instance variables will be assigned when an object is instantiated along with the objects in the Java heap.
public static int value = 123; // preparation phase value initial value is 0. In the initialization phase will become 123.

4. resolve

In this phase, the completion of the operation of a direct conversion symbol reference cited. Action does not necessarily resolve before the initialization operation is completed, there are possible after initialization.

5. Initialize

The last step in the initialization class is loaded, the front loading type, by addition to defining class loader from participation, the remaining operation is completely dominated by the virtual machine in the loading phase and the user application control. To the initialization phase, really started classes defined in Java code.

6. Use

7. Uninstall

II. Describe the principle mechanism JVM loaded Class file?

Java language is a kind of dynamic interpreted language, class (Class) only be loaded into the JVM to run after. When running the specified program, JVM will compile the generated .class file is loaded in accordance with certain rules and requirements into memory, and organized as a complete Java application. The loading process is done by the class loader, specifically, it is the ClassLoader and its subclasses to achieve. Class loader is itself a class, and its essence is the class file is read from the hard disk into memory.

Loading into the class loading to load and display the implicit. Implicitly refer to programs loaded when creating a new object using other means, implicitly calling class loader corresponding to the class is loaded into the JVM. Loading refers to display the required classes loaded into the JVM by calling class.forName () method.

Any project is made up of many classes when the program starts, only the required classes loaded into the JVM, other classes only be used to time will be loaded using this method on the one hand may load faster the cost of memory, on the other hand can save a program is running. Further, in the Java language, each corresponds to a class or interface .class files, which can be seen as one unit can be dynamically loaded, so that when only a portion of the class is modified, only the changes need to be recompiled class can be, without the need to recompile all files, thus speeding up the compilation speed.

In the Java language, loaded class is dynamic, and it will not be a one-time class will all fully loaded before running, but to ensure the base class running (for example, the base class) fully loaded into the JVM, as for other classes, then only loaded when needed.

The main steps classloading:
• Load, find the appropriate class file based search path, and then import.
• links, links can be divided into three small steps:
• Check, check the correctness of the class file to be loaded.
• Prepare, to the class static variable allocation of storage space.
• resolve the symbolic references converted to a direct reference (this step is optional)
• initialization. Perform initialization of static variables and static code block.

Three Java memory allocation.

• Register: we can not control.
• static fields: static members static definition.
• constant pool: compile time is determined and stored in the .class files (Final) and constant values ​​of some modified text symbol references (fully qualified name of the class and interface, the name and descriptor fields, and the method name and descriptor ).
• Non-RAM storage: permanent hard disk storage space.
• heap memory: new objects and arrays created by the Java virtual machine to manage the automatic garbage collection, slow access speed.
• Stack memory: basic types of variables and object reference variables (access heap memory address space), fast, can be shared, but the size and survival must be determined, lack of flexibility.

Java heap structure look like? What is permanent heap-generation (Perm Genspace)?
JVM heap is the runtime data area, all class instances and arrays is allocated on the heap memory. It was created when the JVM starts. Target share of heap memory is also recovered by the garbage collector is an automatic memory management systems.
Heap memory is an object composed of live and dead. Live objects is the application can access, it will not be garbage. The object of death is the object of the application is not accessible yet have not been out of the garbage collector. Until before the garbage collector to reclaim these objects fall, they will always occupy heap memory space.

What four .GC that? Why should there be GC?

GC is a garbage collection means (GabageCollection), memory handling is where programmers prone to problems, and forget or false memory recovery program will lead to instability or even collapse of the system, provided Java GC function automatically detects the object exceeds role domain so as to achieve the purpose of automatically reclaim memory, Java language does not provide a display method operation of the release of allocated memory.

V. Brief Java garbage collection mechanism.

In Java, the programmer is not required to release a displayed object memory, but executed by the virtual machine itself. In the JVM, there is a garbage collector thread, it is a low priority, under normal circumstances will not be implemented only when the virtual machine is idle or the current lack of heap memory, will trigger the execution, those who have not been any sweeping surface referenced object, and adds them to the collection to be recovered, recovered.

VI. How to determine whether an object is alive? (GC method of determination or object)

Determine whether an object is alive in two ways:

1. Reference counting

Reference counting is called to set a reference to each object counter, whenever there is a place to reference the object, the counter will be incremented by one, when referring to fail, a counter is decremented. When an object's reference count is zero, indicating that this object is not referenced, or "dead objects", it will be garbage collection.
Reference counting has a flaw that can not resolve the circular reference problem, that is, when the object A references object B, the object B and referrer object A, then the time A, B object reference counter is not zero, it can not cause complete garbage collection, so the mainstream of the virtual machine is not used in this algorithm.

2. reachability algorithm (reference chain method)

Idea of ​​the algorithm is: an object is called from a GC Roots begin searching down, if an object is not connected to any reference GC Roots chain, then this object is not available.
GC Roots can be used as objects in Java are the following:
• Virtual Machine stack objects referenced
• area class method static properties referenced objects
• Method object referenced by the constant pool area
• JNI native method stacks objects referenced
While these algorithms may determine whether an object can be recovered, but when the above conditions are satisfied, a ratio of the object is not necessarily recovered. When an object is unreachable GC Root, the object will not immediately be recovered, but a reprieve for the stage, to the recovery of the real need to go through two marks.

If the object is not referenced in reachability analysis with GC Root of the chain, then the time will be the first mark and conduct a screening, screening condition is whether it is necessary to perform the finalize () method. When the object does not cover the finalize () method has been called or virtual machine, then that is not necessary. If the object is necessary to perform a finalize () method, then the object will be placed in a called F-Queue to queue, the virtual trigger a Finalize () thread to execute, this thread is a low priority, and virtual machine will not promise has been waiting for it to run to completion, it is as if finalize () or slow implementation of a deadlock occurs, it will result in F-Queue column has been waiting for, resulting in a collapse of the memory recovery system. GC F-Queue object is in a second labeled, then, the object will be removed "will recover" set wait recovered.

VII. Advantages and principles of garbage collection. And consider two kinds of recovery mechanisms.

Java language in a notable feature is the introduction of garbage collection mechanism, so that C ++ programmers the most headache solved the problem of memory management, which allows Java programmers in the preparation of the program no longer need to consider memory management. Because there is a garbage collection mechanism, Java objects are no longer in the "scope" concept, and only the object reference have no "scope." Garbage collection can effectively prevent memory leaks, efficient use of memory can be used. Garbage collector is usually as a separate low-level thread to run, heap memory have died a long time without the use of a clear and recovery under unpredictable circumstances, the programmer can not be called real-time garbage collector for a All objects or objects for garbage collection.
Recovery mechanisms have a generation copy garbage collection and marking garbage collection, incremental garbage collection.

VIII. What is the basic principle is that the garbage collector? The garbage collector can immediately reclaim memory? Is there any way the initiative to inform the virtual machine garbage collection?

For GC, when a programmer to create an object, GC began monitoring address, size and use of the object. Typically, GC using the records have all the objects and managing the heap (heap) to the embodiment of FIG. In this way identify which objects are "reachable", which objects are "unreachable." When the GC identify targets for the "unreachable", GC has the responsibility to reclaim the memory space. can. Programmers can be performed manually System.gc (), notify the GC run, but the Java language specification does not guarantee that GC will perform.

Nine. Java memory leak it will simply describe.

The so-called memory leak or a variable that refers to an object is no longer used by the program it has been occupied in memory. Java has garbage collection mechanism that ensures that when a object is no longer referenced by that object becomes an orphan when the object is garbage collector will automatically be removed from memory. Because Java uses garbage collection has managed to chart the way, you can eliminate the problem of reference cycles, for example, there are two objects refer to each other as long as they do not reach the root process, then the GC is also possible to recover them.

Case of memory leaks in Java: Object long life cycle of short life cycle holds references to objects it is a memory leak may occur, despite the short life cycle of an object is no longer needed, but because of the long lifetime of an object held by its reference cause can not be recycled, which is what happens in the scene Java memory leaks, quite literally, a programmer might create an object, the future no longer have to use this object, which has been cited, but that is not the object useless is garbage collected, which is the case in java memory leak may occur, for example, cache system, we load an object in the cache (for example, on a global map object), then it has no longer used, this object has been cached references, but is no longer used.

Java memory leaks checking in, be sure to let the program will complete the implementation of the various branches of cases to the end of the program, and then see if an object has been used, and if not, to determine the object belongs to a memory leak.

If the method instance of an object class returns an external instance of an object of an inner class, the class object inside long been cited, even if the outer class instance of the object is no longer used, but because of persistent internal class instance object outside the class, this external object will not be garbage collection, which can also cause memory leaks.

Another case of memory leaks: When an object is stored into the HashSet collection in the future, they can not modify those involved in the field to calculate the hash value of the object, otherwise, the hash value of the object is modified and stored into the first HashSet when the hash value set is different, in this case, even if the object contains the method that is currently used as a reference parameter to retrieve a set of objects HashSet, find the object it will also return a result, which also leading to the current object can not be deleted from the HashSet collection alone, cause a memory leak.

X. deep copy and shallow copy.

Simply put, it is to copy, clone.
Person p = new Person ( "John Doe");
Shallow copy is a member of the data object is a simple assignment, if the dynamic members, or will give an error pointer exists.
Deep copy of the object is present in the dynamic member or a pointer to re-open the memory space.

Eleven. System.gc () and Runtime.gc () will do anything?

These two methods are used to prompt JVM garbage collection. However, immediately begin or delayed garbage collection is dependent on the JVM.

Twelve. Finalize () method is invoked when? What is the purpose destructor (finalization) is?

Garbage collector (garbage colector) determine the recovery of an object, the object will run finalize () method in Java but unfortunately, if the memory is always sufficient, then the garbage collector might never be, that filalize () may never be executed, apparently we expect it to do finishing work is unreliable. Then finalize () what to do it? Its primary purpose is to recover special channel application memory. Java program has garbage collector, memory problems so programmers do not have to worry about under normal circumstances. But there is a JNI (Java Native Interface) to call non-Java programs (C or C ++), finalize () job is to recover the memory of this section.

XIII. If the referenced object is set to null, the garbage collector if the object immediately release the memory occupied?

Not, the next garbage collection cycle, the object will be recovered.

XIV. What is distributed garbage collection (DGC)? How does it work?

DGC is called distributed garbage collection. RMI DGC do use automatic garbage collection. Because RMI remote object contains a reference to cross virtual machine, garbage collection is difficult. DGC using reference counting algorithm to provide automatic memory management to remote objects.

XV. What is the difference between serial (serial) collectors and throughput (throughput) is a collector?

Throughput collector uses a parallel version of the new generation garbage collector, which for applications medium-sized and large-scale data. The serial collector for most small applications (probably need about 100M memory on modern processors) is sufficient.

XVI. In Java, when an object can be recycled garbage?

When the object becomes inaccessible to the current applications that use this object when this object can be recycled.

XVII. Description of Java memory allocation and recovery policy rates and Minor GC and MajorGC.

• Object priority in the allocation of the heap in the Eden area
• large objects directly into the old year
• Long-term survival of the object will go straight years old
When the Eden area is not enough space allocation, virtual machines perform a Minor GC. Minor GC Eden usually occurs in new generation region, the short lifetime of the object in this zone, the higher frequencies often occurs and Gc, faster recovery;
Full GC / Major GC occurred in the old years, under normal circumstances, when the trigger will not trigger GC years old Minor GC, but through configuration, you can conduct a Minor GC This can speed up the recovery rate of old age before the Full GC.

XVIII. Permanent behalf of the JVM garbage collection will happen?

Garbage collection does not occur in the permanent generation is full or if permanent behalf of more than the critical value, it will trigger full garbage collection (Full GC).
Note: Java 8 has been removed permanently generations, added a new native memory area called metadata area.

XIX. The method of garbage collection in Java What?

Mark - Clear:

This is the most basic garbage collection algorithm, according to the name you know, it's what is thought to be recycled object tag, then uniform recycling. This method is simple, but there will be two main issues:

1. Efficiency is not high, marking and removal efficiency is very low;
2. will generate a lot of discrete memory fragmentation, causing the program later in the allocation of large objects, because there is no sufficient contiguous memory prematurely trigger a GC operation.

Replication algorithm:

In order to address efficiency issues, by the copy algorithm available memory capacity is divided into two equal parts, and then uses only one of them, when a copy runs out of memory, it will also live objects to the second memory block, and After a clear first-time memory, and then copy the object on the second block to the first block. But this way, the cost is too high memory, each basically have to waste a general memory.

Thus the algorithm is improved, the memory area is no longer 1: 1 to divide, but the memory is divided into 8: 1: 1 of three parts, a larger share of the memory area cross-Eden, two small remainder memory area called Survior area. Eden precedence every time zone, if the Eden area is full, the object will be copied to the second memory block area, and then clear the Eden area, this time surviving if too many objects, so that when Survivor is not enough, these objects will pass guarantee mechanism for distributing copies to the old era. (Java heap is divided into the old and the new generation's)

Mark - finishing:

The algorithm to solve the mark - sweep, a large amount of memory fragmentation problems; when the object is high survival rates, but also solve the problem of efficient replication algorithm. Its difference is now clear recoverable object moves to the object when the one end, and then removed the object other than the end boundary, so that a memory fragmentation is not generated.

Generational collection:

Now they use a virtual machine garbage collection in this way, it is based on the life cycle of the object, the heap into the new generation and the old era. In the new generation, because of the short lifetime of the object, there will be a large number of objects recovered each time to die, then the time on the use of replication algorithm.

The old era of high survival rate target, no additional space allocation guarantee.

XX. What is the class loader class loader What?

Realized by code block based naming authority acquired binary byte stream class called a class loader.
There are about four types of loader:
• Start class loader (Bootstrap ClassLoader) is used to load the core Java class libraries, the Java program can not be directly referenced.
• extension class loader (extensions class loader): It is used to load a Java extension library. Implementation of the Java Virtual Machine will provide an extensive library directory. This class loader to find and load Java classes in this directory.
• System class loader (system class loader): it is to load Java classes according to the class path Java applications (CLASSPATH). In general, class Java applications are made to complete it loaded. You can get it by ClassLoader.getSystemClassLoader ().
• User-defined class loader, implemented by inheriting class java.lang.ClassLoader way.

Twenty-one. Parent class loader delegation model mechanism?

When a class is received load request class, the class would not themselves go to the load, but it will be delegated to the parent class, a parent class to load, if the parent class can not be loaded at this time, back to the subclass, the subclass loaded to complete the class.

to sum up

All interview questions are not immutable, especially as first-tier manufacturers, the above interview Zhenti just give you a reference function, the most important is to give themselves a reserve of knowledge, be prepared.


To share in 2019 finishing manufacturers JVM face questions and study notes the information pdf document and knowledge points learning road map brain thinking as well as to explain video JVM. Welcome to the concern of my male species ho [programmers] marks the beginning of the article will be updated on the inside, documentation will be on the inside.


At last

Welcome to share with everyone, like the article I remember concern thumbs forward yo, thanks for the support!

Guess you like

Origin juejin.im/post/5de65ff66fb9a016502f297b