First, JVM performance optimization

1. Java class loading process

Java class loading goes through seven processes:

Load 1.1.

Loading is the first class loading process. During this phase, three things are done:

1. Get the binary stream of a class by its fully qualified name. 2. Transform the static storage structure in the binary stream into a method to run the runtime data structure. 3. Generate a Class object in memory for the data access of the Class.

1.2. Verify

The purpose of validation is to ensure that information in the byte stream of the Class file is not returned to the virtual machine. In this stage, the following four-clock verification is mainly completed:

1. File format verification: verify whether the byte stream complies with file specifications, for example, whether the primary and secondary versions are within the range of the current VM, and whether the constants in the constant pool have unsupported types. Metadata validation: Semantic analysis of information described by bytecode, such as whether the class has a parent class, whether it integrates classes that are not inherited, etc. 3. Bytecode verification: it is the most complicated stage in the whole verification process. Through the analysis of the verification data flow and control flow, the correctness of the program semantics is determined, mainly for the verification of the method body. Such as: method of type conversion is correct, jump instruction is correct. 4. Symbolic reference validation: This action occurs later in the parsing process to ensure that the parsing action is performed correctly.

1.3. Preparation

The preparation phase allocates and initializes memory for static variables of the class to default values, which will be allocated in the method area. The preparation phase does not allocate memory for instance variables in the class, which will be allocated in the Java heap along with the object when it is instantiated.

public static int value=123; // During the preparation phase value the initial value is 0. It only becomes 123 during initialization.Copy the code

1.4. Analytical

This stage mainly completes the symbolic reference to direct reference conversion action. The parse action is not necessarily before the initialization action is complete, but may also be after initialization.

1.5. Initialization

Initialization is the last step of class loading. The previous class loading process is completely dominated and controlled by the virtual machine, except that the user application can participate in the loading phase through the custom class loader. During the initialization phase, you actually start executing the Java program code defined in the class.

1.6. Use

1.7. Uninstall

2. Java memory allocation

Register: We have no control. Static field: Static member defined by static. Constant pool: Symbolic references to final constant values and some text modifications (fully qualified names of classes and interfaces, field names and descriptors, method and name and descriptors) that are determined and saved ina. Class file at compile time. Non-ram storage: Permanent storage space such as hard disks. Heap memory: Objects and arrays created by new are managed by the Java virtual Machine automatic garbage collector and are accessed slowly. Stack memory: Variables of basic types and reference variables of objects (the access address of the heap memory space) are fast and can be shared, but the size and lifetime must be determined, which is inflexible. 2.1. What is the structure of a Java heap? 2 What are persistent generations in the heap? The JVM’s heap is the run-time data area on which all instances and arrays of classes are allocated memory. It is created when the JVM starts. The heap memory occupied by objects is reclaimed by the automatic memory management system, which is the garbage collector. Heap memory is made up of living and dead objects. Live objects are accessible to the application and are not garbage collected. Dead objects are objects that are inaccessible to the application and have not yet been collected by the garbage collector. These objects occupy heap memory space until the garbage collector collects them.

Describe how the JVM loads Class files

The Java language is a dynamic interpreted language, and classes cannot run until they are loaded into the JVM. When the specified program is run, the JVM loads the compiled.class file into memory according to requirements and certain rules and organizes it into a complete Java application. This loading process is done by the ClassLoader, specifically by the ClassLoader and its subclasses. The classloader itself is a class that essentially reads class files from hard disk into memory. Class loading methods are classified into implicit loading and display loading. Implicit loading means that when a program creates an object using new, for example, it implicitly calls the class loader to load the corresponding class into the JVM. Display loading refers to loading the required classes into the JVM by calling the class.forname () method directly.

Any project is composed of many classes. When the program is started, only the required classes are added to the JVM, and other classes are only loaded when they are used. This method can speed up the loading on the one hand, and save the memory overhead when the program is running. In addition, in the Java language, there is a.class file for each class or interface, which can be viewed as a unit that can be loaded dynamically, so when only part of the class is changed, you only need to recompile the changed class, rather than recompile all the files, thus making the compilation faster. In the Java language, class loading is dynamic. Instead of loading all classes at once and then running them, it ensures that the base classes (such as the base classes) in which the program is running are fully loaded into the JVM, and other classes are loaded as needed. The main steps of class loading:

1. Loading. Find the corresponding class file according to the search path, and then import. 2. The link. The link can be divided into three steps: 3. Check that the class file to be loaded is correct. 4. Prepare, allocate storage space for static variables in the class. 5. Parse and convert symbolic references to direct references (this step is optional) 6. Initialize. Performs initialization work on static variables and static code blocks.

4. What is GC? Why GC?

GC is garbage collection, memory processing is the programmer prone to problems, forget or wrong memory collection will lead to program or system instability or even crash,Java provides GC function can automatically monitor objects The Java language does not provide a display operation for freeing allocated memory if it is out of scope to automatically reclaim memory.

5, Brief introduction of Java garbage collection mechanism)

In Java, programmers do not need to display to free the memory of an object; the virtual machine does it itself. In the JVM, there is a garbage collection thread, which is low priority and does not execute normally, but only when the VIRTUAL machine is idle or when the front heap is out of memory, which is triggered to scan objects that are not referenced by any of them and add them to the collection for collection.

6. How to determine if an object is alive? (or GC object determination method)

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

6.1. Reference counting

Reference counting sets a reference counter for each object, incrementing the counter whenever the object is referenced somewhere, and decrement it when the reference fails. When an object’s reference counter is zero, the object is not referenced, which is a “dead object” and will be garbage collected. Reference counting method has A defect that it cannot solve the problem of circular reference. That is, when object A refers to object B, object B refers to object A, then the reference counter of object A and object B is not zero, and garbage collection cannot be completed. Therefore, mainstream virtual machines do not use this algorithm.

6.2. Reachability Algorithm (Chain of References)

The idea is to search down from an object called GC Roots, and if an object is not connected to GC Roots by any reference chain, the object is not available. There are several objects that can be used as GC Roots in Java:

1. Objects referenced in the VM stack

2. Objects referenced by static properties of the method area class • Objects referenced by the constant pool of the method area

Although these algorithms can determine whether an object can be reclaimed, an object ratio is not necessarily reclaimed when the above criteria are met. When an object is unreachable to GC Root, it is not immediately recycled, but rather in a dormant phase, and is marked twice before it can actually be recycled. If the object does not have a reference chain with GC Root in the reachability analysis, then it will be marked for the first time and filtered based on whether it is necessary to execute the Finalize () method. Objects that do not override the Finalize () method or have already been called by a virtual machine are considered unnecessary. If it is necessary for the object to execute finalize(), then the object will be put ina pair Queue called f-queue, and the virtual machine will trigger a Finalize() thread to execute, which is of low priority, and the virtual machine will not commit to wait until it is finished, because if When Finalize () is executed slowly or deadlocks occur, the F-queue will wait forever and the memory reclamation system will crash. The GC marks the object in the f-queue a second time, at which point the object is removed from the collection to be collected.

7, the advantages and principles of garbage recycling) and consider two recycling mechanisms)

A notable feature of the Java language is the introduction of garbage collection mechanism, which makes C++ programmers’ most troublesome memory management problem solved. It makes Java programmers no longer need to consider memory management when writing programs. Thanks to a garbage collection mechanism, objects in Java are no longer scoped; only references to objects are scoped. Garbage collection is an effective way to prevent memory leaks and use usable memory efficiently. The garbage collector is usually run as a single low-level thread, cleaning and collecting objects that have died or not been used for a long time in the heap in unexpected circumstances. The programmer cannot call the garbage collector in real time to collect an object or all objects. Collection mechanisms include generational replication garbage collection, tagged garbage collection, and incremental garbage collection.

What is the basic principle of garbage collector? Can the garbage collector reclaim memory right away? Is there any way to proactively notify the virtual machine for garbage collection?

In the case of the GC, when a programmer creates an object, the GC starts monitoring the address, size, and usage of the object. In general,GC records and manages all objects in the heap in a directed graph. This is a way to determine which objects are “reachable” and which are “unreachable”. When the GC determines that some objects are “unreachable,” it is the GC’s responsibility to reclaim those memory Spaces. You can. Programmers can manually execute System.gc() to tell the GC to run, but the Java language specification does not guarantee that the GC will execute.

9. Are there memory leaks in Java? Please briefly describe)

A memory leak is when an object or variable that is no longer being used by a program remains in memory. Java has a garbage collection mechanism that ensures that when an object is no longer referenced, that is, orphaned, it is automatically removed from memory by the garbage collector. Because Java uses a directed graph for garbage collection management, it eliminates the problem of reference loops. For example, if two objects refer to each other, as long as they are unreachable from the root process, the GC can reclaim them as well, as can be seen in the following code:

*/ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub try { gcTest(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("has exited gcTest!" ); System.in.read(); System.in.read(); System.out.println("out begin gc!" ); for(int i=0; i<100; i++) { System.gc(); System.in.read(); System.in.read(); } } private static void gcTest() throws IOException { System.in.read(); System.in.read(); Person p1 = new Person(); System.in.read(); System.in.read(); Person p2 = new Person(); p1.setMate(p2); p2.setMate(p1); System.out.println("before exit gctest!" ); System.in.read(); System.in.read(); System.gc(); System.out.println("exit gctest!" ); } private static class Person { byte[] data = new byte[20000000]; Person mate = null; public void setMate(Person other) { mate = other; }}}Copy the code

A memory leak situation in Java: a memory leak occurs when a long-life object holds a reference to a short-life object. Although the short-life object is no longer needed, it cannot be reclaimed because the long-life object holds a reference to it Memory leaks occur in the scene, in layman’s terms, as programmers may have in creating an object, no longer since I have been using this object, the object has been used, namely the object useless but not reclaimed by the garbage collector, this is possible memory leaks in Java, for example, caching system, we loaded a right Like putting it in the cache (for example, in a global map object) and then never using it again, the object is always referenced by the cache but no longer used. To check for a memory leak in Java, make sure that the program executes all branches to the end of the program, and then see if an object is used. If not, the object is considered a memory leak. If an external object instance of a class of the method returns an inner class instance of the object, the inner class object was cited for a long time, even if the external class does not use this instance objects, but as a result of the inner class lasting external instance objects of a class, the external class object will not be garbage collected, this will cause memory leaks. The following content from the Internet (one of the main characteristic is to empty stack elements, it is not completely removed from the array, but reduce the total number of storage, I can write better than this, when remove an element, by the way, let it disappear from the array to the element’s location value can be set to null) : I really can’t think of a more classic example than that stack, so I have to cite someone else’s example. The following example is not what I thought of, but what I read in a book. Of course, if I didn’t read in a book, I might have thought of it myself after a while, but no one would believe me if I said I thought of it myself.

public class Stack { private Object[] elements=new Object[10]; private int size = 0 ; public void push(Object e){ ensureCapacity(); elements[size++] = e; } public Object pop(){ if( size == 0) throw new EmptyStackException(); return element s[--size]; } private void ensureCapacity(){ if(elements.length == size){ Object[] oldElements = elements; elements = new Object[2 * elements.length+1]; System.arraycopy (oldElements,0, elements, 0, size); }}}Copy the code

The above principle should be very simple, if we add 10 elements to the stack, and then all pop up, although the stack is empty, there is nothing we want, but this is an object that can not be recycled, this meets the two conditions of memory leak: useless, can not be recycled. But it doesn’t really matter if there’s such a thing, because if the stack is used less, we’re wasting a couple of K’s of memory, so it doesn’t matter if we’re using G’s, and it’s going to be recycled pretty quickly. Let’s look at two examples.

public class Bad{ public static Stack s=Stack(); static{ s.push(new Object()); s.pop(); S.ush (new Object()); // The above object can be recycled, such as self-healing}}Copy the code

Because it’s static, it’s there until the program exits, but we can also see that it has a self-healing function, which means that if you have 100 objects on your Stack, you’re going to have 100 objects that can’t be recycled at most and that should make a lot of sense, The Stack holds 100 references inside, and the worst case scenario is that they’re all useless, because the old references disappear as soon as we start new ones! Another case of memory leak: once an object is stored in a HashSet, the fields in the object that contributed to the hash cannot be modified. Otherwise, the modified hash value of the object is different from the original hash value stored in the HashSet. In this case, even in the case of The Contains method retrieves an object from the HashSet using the current reference of the object as an argument. The contains method also returns a result that the object is not found. This also causes the current object to be unable to be removed from the HashSet separately, causing a memory leak.

Deep copy and shallow copy

In a nutshell, it is replication and cloning.

Person p=new Person(" Person ");Copy the code

Shallow copy is a simple assignment of data members in an object, and an error is reported if there are dynamic members or Pointers. Deep copy is the relocation of dynamic members or Pointers that exist in an object.

What does system.gc () and Runtime.gc() do?

These two methods are used to prompt the JVM for garbage collection. However, whether to start garbage collection now or delay it is up to the JVM.

When will finalize() method be called? What is the purpose of finalization?

When the garbage colector decides to recycle an object, it runs the Finalize () method of that object. Unfortunately in Java, if memory is always full, garbage collection may never happen, which means filalize() is possible It is never implemented, and it is obviously not reliable to expect it to finish the job. So what does Finalize () do? Its main use is to reclaim memory requested by a special channel. Java programs have garbage collectors, so memory problems are generally not a programmer’s concern. However, there is a JNI(Java Native Interface) that calls non-Java programs (C or C++), and finalize() ‘s job is to reclaim this part of memory.

If the object reference is set to NULL? Does the garbage collector immediately free memory occupied by objects?

No, the object will be recyclable in the next garbage collection cycle.

What is Distributed Garbage Collection (DGC)? How does it work?

DGC is called distributed garbage collection. RMI uses DGC for automatic garbage collection. Because RMI contains references to remote objects across virtual machines, garbage collection is difficult. DGC uses reference counting algorithms to provide automatic memory management for remote objects.

What is the difference between a serial collector and a throughput collector?

The throughput collector uses a parallel version of the new generation garbage collector for medium – and large-data applications. The serial collector, on the other hand, is sufficient for most small applications, which require roughly 100 megabytes of memory on modern processors.

16. In Java? When can objects be garbage collected?

When an object becomes untouchable to the application that currently uses it, it can be reclaimed.

17, Brief introduction of Java memory allocation and collection policy and Minor and Major GC)

1. Objects are allocated in the Eden area of the heap first

2. Big objects go straight to the old age

If the Eden area does not have enough space to allocate, the virtual machine performs a Minor GC. Minor GC usually occurs in the Eden area of Cenozoic era. The objects in this area have a short lifetime, and tend to have a high frequency of GC occurrence and a relatively fast recovery rate. Full /Major GC occurs in the old generation. Normally, old GC does not trigger a Minor GC, but can be configured to do a Minor GC before Full GC to speed up old GC collection.

18. Does garbage collection occur in JVM permanent generations?

Garbage collection does not occur in the permanent generation, and Full garbage collection (Full GC) is triggered if the permanent generation is Full or the threshold is exceeded. Note: Java 8 has removed permanent generations and added a new native memory area called the metadata area.

What are the methods of garbage collection in Java?

Mark-sweep: This is the most basic of the garbage collection algorithms and, as the name suggests, the idea is to mark which objects are to be collected and then collect them collectively. This approach is simple, but there are two main problems:

1. Low efficiency, low efficiency of marking and cleaning; 2. A large number of discrete memory fragments can be generated, causing a GC action to be triggered prematurely when the program allocates larger objects because there is not enough contiguous memory. Replication algorithm: in order to solve the problem of efficiency, will be available memory replication algorithm according to the capacity is divided into two equal parts, and then using only one piece, every time when a piece of memory used up, will also live to like copied to the second piece of memory, then one-time clear out the first block of memory, and then on the second object is copied to the first block. But this way, the cost of memory is too high, each time basically waste half of memory. Therefore, the algorithm is improved. Instead of 1:1, the memory region is divided into 8:1:1 three parts. The larger memory region is Eden region, and the remaining two smaller memory regions are called Survior region. If Eden is full, objects will be copied to the second memory block, and then Eden will be cleared. If there are too many surviving objects so that there are not enough survivors, these objects will be copied to the old age through the allocation guarantee mechanism. (Java heap is divided into new generation and old generation) mark-collation: this algorithm is mainly to solve the problem of mark-clearing, resulting in a large number of memory fragments; When the object survival rate is high, the efficiency of the replication algorithm is also solved. The difference is that it now moves the recyclable objects to one end when it clears objects, and then clears objects beyond the end boundary, so there is no memory fragmentation. Generational collection: Most current virtual machine garbage collection uses this method, which divides the heap into new generation and old generation based on the life cycle of the object. In the new generation, due to the short life of objects, a large number of objects will die each time the callback, so the replication algorithm is used. Subjects in the old age had a higher survival rate and no extra space to allocate guarantees.

20. What is a class loader? What are class loaders?

A block of code that implements retrieving the binary stream of a class by its permission name is called a classloader. There are four main types of loaders:

1. BootstrapClassLoader (BootstrapClassLoader) is used to load Java core class libraries, which cannot be directly referenced by Java programs.

2. Extensions Class Loader: It is used to load Java extension libraries. The Implementation of the Java Virtual machine provides an extension library directory. The class loader finds and loads Java classes in this directory.

3. System Class Loader: It loads Java classes according to the CLASSPATH of the Java application. In general,Java application classes are loaded by it. Through this. GetSystemClassLoader () to get it.

4. User-defined ClassLoader is implemented by inheriting java.lang.ClassLoader.

Class loader parent delegate model mechanism?

When a class receives a class loading request, it does not load the class first. Instead, it delegates to the parent class, and the parent class loads the class. If the parent class fails to load the class, the parent class sends feedback to the child class, and the child class completes the class loading.