preface

With the development of the Internet, Java applications have strict requirements for high concurrency, high availability, fast response, etc., which are actually related to THE JVM. Internet manufacturers have higher and higher requirements for concurrency and performance. Improving Java application performance is becoming increasingly important for JVM performance tuning, which is designed to achieve higher throughput with less memory. This is a mind map for JVM performance tuning. This is a mind map for JVM performance tuning.Java Virtual Machine: Advanced JVM Features and Best Practices Study Notes 400 pages PDF summary. 台湾国

Memory structure

Thread shared area

Heap (for holding object instances)

1. Cenozoic Era

(1) Eden District

(2) Survivor(from) zone (set Survivor to reduce the number of objects sent to the old age)

(3) Survivor(to) zone (Two Survivor zones are set to solve the problem of fragmentation)

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

2. The old days

Old age: New generation =2:1

Methods area

1. Runtime constant pool

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

(2) Store information

Symbolic reference

1) Symbol references contain constants

  • Class symbol reference

  • Method symbol reference

  • Field symbol reference

2) Concept explanation

When a Java class (let’s say People) is compiled into a class file, if People references the Tool class, but at compile time People does not know the actual memory address of the referenced class, so symbolic references are used instead. When the People class is loaded by the class loader, the real memory address of the Tool class can be obtained from the virtual machine. Therefore, the symbol org.simple.Tool can be replaced with the real memory address of the Tool class, and the address can be directly referenced. That is, a symbolic reference is used to replace the reference class at compile time and the virtual machine obtains the actual address of the reference class at load time. A set of symbols describing the referenced object, which can be any literal, as long as it is used unambiguously to locate the object. Symbolic references are independent of the memory layout implemented by the virtual machine, and the target of the reference is not necessarily already loaded into memory.

literal

  • Text String (String a = “ABC “, which is the literal)

  • Eight basic types (int a = 1; This one is literally.)

  • A constant declared final

2. Static variables

3. Final type constants

4. Class information

  • The full valid name of the class

  • Return value type

  • Modifiers (public, private…)

  • The variable name

  • The method name

  • Method code

  • The full valid name of the type’s immediate parent (unless the type is interface or java.lang.Object, in which case there is no parent)

  • An ordered list of the direct interfaces to the class

Thread private area

The virtual machine stack

1, the stack frame

(1) Dynamic link

  • Symbolic and direct references are parsed and linked at run time, called dynamic linking.

  • The premise is that each stack frame contains a reference to the runtime constant pool to support dynamic linking.

(2) Operand stack

Stores data during the execution of the Java virtual machine

(3) Local variation scale

1) The memory space required by the local variable table is allocated at compile time. When entering a method, how much local variable space the method needs to allocate in the frame is completely determined, and the size of the local variable table does not change during the method run.

2) Stored information

  • Basic data types

  • Object reference

  • ReturnAddress type

(4) The method returns the address

1) Where the method is called

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

3) Method exit possible operations

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

  • Pushes the return value (if any) into the operand stack of the caller’s stack frame

  • Adjust the value of the PC counter to point to an instruction following the method call instruction

2, abnormal

Thread request stack depth greater than allowed by virtual machine (StackOverflowError)

Failed to allocate enough memory for dynamic JVM scaling (OutOfMemoryError)

When compile the program Code, how much local variables in the stack frame, how deep the operand stack are completely determined, and the attributes of Code written to the method table, so a stack frame needs to how much memory allocation, not affected by the program run time variable data, but only depends on the specific virtual machine implementation.

Local method stack

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

Program counter

1. Specifies the number of bytecode lines executed by the current thread if the thread is executing a Java method

2. This memory region is the only one where OutOfMemoryError does not occur.

3. If the Natvie method is being executed, this counter is null (Undefined).

The three regions have the same life cycle as threads

Direct memory

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

Is not part of the JVM runtime data area, but is frequently used

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

Memory allocation

Objects are allocated in Eden area first

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

Big object goes straight to the old age

The most typical large objects are long strings and arrays.

The long term survivor enters the old age zone

If the object survives after Eden is born and passes the first Minor GC and can be accommodated by Survivor, it is moved to Survivor space and the object age is set to 1. Each time the object survives a Minor GC in Survivor, its age increases by 1. When its age increases to a certain level (default: 15)_, it is promoted to the old age.

Object age dynamic determination

If the combined size of all objects of the same age in a Survivor space is greater than half of the size in a Survivor space, objects older than or equal to that age can go straight to the old age

Space allocation guarantee

Before Minor GC occurs, the virtual machine checks to see if the maximum available contiguous space of the old generation is greater than the total space of all objects of the new generation. If this condition is true, then Minor GC is guaranteed to be safe. If this is not true, the virtual machine checks the HandlePromotionFailure setting to see if the guarantee failure is allowed. If so, it continues to check whether the maximum available contiguous space of the old age is greater than the average size of the objects promoted to the old age. If so, a Minor GC is attempted, although this Minor GC is risky, and a Full GC is attempted if the guarantee fails. If less than, or if the HandlePromotionFailure setting does not allow risk, then do a Full GC instead.

Memory recovery

Minor GC

The characteristics of

Occurred in the Cenozoic era, occurred more frequently, the execution speed is faster

The trigger condition

  • The space in Eden is insufficient

  • Space allocation guarantee

Full GC

The characteristics of

Occurred in the old era, less occurrence, slower execution

The trigger condition

  • Call System. The gc ()

  • Old age area space is insufficient

  • Space allocation guarantee failed

  • There is not enough space for persistent generations (method areas) in JDK 1.7 or earlier

  • When THE CMS GC deals with floating garbage, if the new generation space is insufficient, the space allocation guarantee mechanism will be adopted; if the old generation space is insufficient, the Full GC will be triggered

Out of memory

The program did not have enough memory when applying for memory. Procedure

How memory overflow is constructed

Stack overflow

OutOfMemoryError: Keep creating objects

Stack overflow

StackOverflowError: Enlarges the table of local variables, such as unreasonable recursion

OutOfMemoryError: Keep creating threads

Method area and runtime constant pool overflow

OutOfMemoryError: constantly adding constants to the constant pool using the string.intern () method, such as string.valueof (i++).intern()

Native memory overflowed directly

A memory leak

The program could not release the allocated memory. Procedure

why

Long-life objects hold references to short-life objects

For example, if you set ArrayList to static variables, objects in the container cannot be freed until the program ends, causing a memory leak

Connection not closed

For example, database connections, network connections, and IO connections, the garbage collector will reclaim the corresponding object only after the connection is closed.

The variable is not scoped properly

For example, 1. The definition of a variable is larger than its scope, and 2. If the object is not set to NULL in time

The inner class holds the outer class

Java’s non-static inner classes are created in such a way that they implicitly hold a reference to the outer class, which by default is a strong reference, so if the inner class lives longer than the outer class, the program can easily leak memory

The solution

  • Define the inner class as static

  • Reference an instance of an anonymous inner class with a static variable

  • Or put an instantiation of an anonymous inner class into a static method of an outer class

Hash value change

In a collection, if you change the fields in an object that participate in the calculation of the hash value, you will not be able to remove the current object individually from the collection, causing a memory leak

Frequently seen exam

1. Is there a memory leak in Java? Please describe it briefly.

Will be. Memory leaks can occur when you implement heaped data structures yourself.

2, In 64-bit JVMS, int length is the majority.

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

What are the differences between Serial and Parallel GC?

Serial and Parallel both cause stop-the-world during GC execution. The main difference between them is that the Serial collector is the default copy collector and only has one thread for GC, while the Parallel collector uses multiple GC threads for GC.

For 32-bit and 64-bit JVMS, is the length of a variable of type int the majority?

In 32-bit and 64-bit JVMS, variables of type int are the same length, either 32 bits or 4 bytes.

5. The difference between WeakReference and SoftReference in Java?

Although WeakReference and SoftReference are both beneficial to improving the efficiency of GC and memory, WeakReference will be recovered by GC once it loses the last strong reference, while SoftReference cannot prevent collection. But it can be deferred until the JVM runs out of memory.

6. What does the JVM option -xx :+UseCompressedOops do? Why use it

When you migrate your application from a 32-bit JVM to a 64-bit JVM, the heap memory is suddenly increased, almost doubling, as Pointers to objects are increased from 32-bit to 64-bit. This also adversely affects the amount of data cached by the CPU (which is much smaller than memory). Because the main motivation for moving to a 64-bit JVM is the ability to specify a maximum heap size, some memory can be saved by compressing OOP. With the -xx :+UseCompressedOops option, the JVM uses 32-bit OOP instead of 64-bit OOP.

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

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

What is the maximum heap memory for 32-bit and 64-bit JVMS?

In theory, 32-bit JVM heap memory can be up to 2^32, or 4GB, but in practice it is much smaller than that. The GB varies depending on the operating system. For example, the GB is 1.5GB for Windows and 3GB for Solaris. 64-bit JVMS allow you to specify maximum heap memory, theoretically up to 2^64, which is a very large number, and in practice you can specify heap size up to 100GB. Even some JVMS, such as Azul, can have up to 1000GB of heap memory.

What are the differences 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. It is a development tool for Java programs, such as the Java compiler, which also includes the JRE. The JVM stands for Java Virtual Machine, and its responsibility is to run Java applications. JIT stands for Just In Time compilation. When code execution exceeds a certain threshold, Java bytecode is converted to native code. For example, major hot code is quasi-converted to native code, which can greatly improve the performance of Java applications.

Explain Java heap space and GC?

When a Java process is started with a Java command, memory is allocated to it. A portion of memory is used to create heap space, and when objects are created in the program, memory is allocated from the pair space. GC is a process within the JVM that reclaims the memory of invalid objects for future allocation.

Memory area

11. JVM memory area

The JVM memory area is mainly divided into thread private area (program counters, virtual stack, local method area), thread shared area (JAVA heap, method area), and direct memory.

Thread-private data areas have the same life cycle as threads, and are created/destroyed depending on the start/end of the user thread (in Hotspot VM, each thread maps directly to the operating system’s local thread, so the memory of this part of the memory area follows the life/death of the local thread).

Thread shared areas are created/destroyed with the startup/shutdown of the virtual machine.

Direct memory is not part of the JVM runtime data area, but is frequently used: NIO, introduced in JDK 1.4, provides Channel – and buffer-based I/O. It can use Native libraries to allocate out-of-heap memory directly, and then use DirectByteBuffer objects as references to this memory. Java I/O extensions), which avoids copying data back and forth between the Java heap and Native heap, and thus can significantly improve performance in some scenarios.

12. Program counter (thread private)

A small area of memory that is a line number indicator of the bytecode being executed by the current thread. Each thread has a separate program counter. This type of memory is also called “thread-private” memory.

If the Java method is being executed, the counter records the address of the virtual machine bytecode instruction (the address of the current instruction). Null if the Native method is used.

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

13. Virtual stack (thread private)

Is a memory model that describes the execution of Java methods. Each method creates a Stack Frame for storing information such as local variable table, operand Stack, dynamic link, method exit, etc. The process of each method from invocation to completion corresponds to the process of a stack frame being pushed into and out of the virtual machine stack.

Stack frames are data structures used to store data and partial process results. They are also used to handle Dynamic Linking, method return values, and Dispatch exceptions. Stack frames are created as the method is called and destroyed as the method terminates — method completion counts whether the method completes normally or if an exception completes (throwing an exception that was not caught within the method).

Local method area (thread private)

The local method Stack is similar to the Java Stack, except that the VM Stack serves the execution of Java methods, while the Native method Stack serves the execution of Native methods. If a VM implementation uses the C-linkage model to support Native calls, the Stack will be a C Stack. But HotSpot VM simply blends the local method stack with the virtual machine stack.

15. Can you guarantee GC execution?

No, although you can call System.gc() or Runtime.gc(), there is no way to guarantee that gc will execute.

How to obtain the memory used by Java programs? What percentage of the heap is used?

The remaining memory, total memory, and maximum heap memory can be obtained using the memory-related methods in the java.lang.Runtime class. Using these methods you can also get the percentage of heap usage and the amount of heap memory remaining. Runtime.freememory () returns the number of bytes of freeMemory, runtime.totalmemory () returns the number of bytes of totalMemory, and runtime.maxmemory () returns the number of bytes of maximum memory.

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

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

Describe how the JVM loads class files

The loading of classes in the JVM is implemented by classloaders and their subclasses. Classloaders in Java are an important component of the Java runtime system that finds and loads classes in class files at runtime.

Because of Java’s cross-platform nature, a compiled Java source program is not an executable program, but one or more class files. When a Java program needs to use a class, the JVM ensures that the class has been loaded, wired (validated, prepared, and parsed), and initialized. Loading a class refers to reading the data from the class’s.class file into memory, usually by creating a byte array that reads into the.class file and generates a class object corresponding to the loaded class.

After loading, the Class object is not complete, so the Class is not available at this point. When the class is loaded, it enters the connect phase, which consists of three steps: validation, preparation (allocating memory for static variables and setting default initial values), and parsing (replacing symbolic references with direct references). Finally, the JVM initializes the class, including: 1) if the class has a direct parent that has not already been initialized, then initialize the parent first; 2) If there are initializers in the class, execute those initializers in turn.

The loading of classes is done by class loaders, including the root loader (BootStrap), Extension loader (Extension), System loader (System), and user-defined ClassLoader (a subclass of java.lang.classloader).

Since Java 2 (JDK 1.2), the class loading process has adopted the parent delegate mechanism (PDM). PDM ensures the security of the Java platform. In this mechanism, the Bootstrap of the JVM is the root loader, while all other loaders have one or only one parent class loader. The loading of a class is first requested by the parent class loader, and only when the parent class loader is unable to do so is the subclass loader loaded by itself. The JVM does not provide a reference to Bootstrap to a Java program. Here are a few classes

Loader description:

(1) Bootstrap: generally implemented by 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. Its parent loader is Bootstrap.

(3) System: also called application class loader, its parent is Extension. It is the most widely used class loader. It starts from the environment variable CLASspath or system properties

The directory specified by java.class.path that holds classes is the default parent of the user-defined loader.

Garbage collector

What is GC? Why GC?

GC means garbage collection, memory processing is the programmer easy to show problems, forget or wrong memory rollback will lead to instability or even collapse of the program or system, Java provides a GC facility that automatically detects if an object is out of scope to reclaim memory automatically. The Java language does not provide a display operation to free allocated memory. Java programmers do not use a core memory manager because the garbage collector automatically manages it. To request garbage collection, one of the following methods can be called: System.gc() or Runtime.geTruntime ().gc(), but the JVM can mask the garbage collection calls shown offline.

Garbage collection can effectively prevent memory leaks and efficiently use available memory. The garbage collector is typically run as a single, low-priority thread that unpredictably cleans and reclaims dead or unused objects in the heap. Programmers cannot call the garbage collector in real time to collect an object or all objects. In the early days of Java, garbage collection was one of the biggest highlights of Java, because server-side programming needed to effectively prevent memory leaks. However, time has changed, and now Java’s garbage collection mechanism has become a thing of the past. Mobile intelligent terminal users generally feel that iOS system has a better user experience than Android system. One of the deep reasons lies in the unpredictability of garbage collection in Android system.

20. Heap (Heap- thread shared) – run-time data area

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

21. Method area/persistent generation (thread sharing)

Permanent Generation, or Permanent Generation, is used to store classes loaded by the JVM, constants, static variables, and code compiled by the time compiler. HotSpot VM extends GC generation collection to the method section using persistent generations of the Java heap to implement the method section, This allows HotSpot’s garbage collector to manage this part of memory in the same way it manages the Java heap, without having to develop a special memory manager for the method area (the main goal of persistent band memory reclamation is constant pool reclamation and type offloading, so the benefits are generally small).

The Runtime Constant Pool is part of the method area. The Constant Pool Table is used to store various literals and symbolic references generated at compile time. This part of the Constant Table is stored in the runtime Constant Pool of the method area after the Class is loaded. The Java virtual machine has strict rules on the format of each part of a Class file (including, of course, the constant pool), and each byte must be used to store what data must conform to the specification before it is accepted, loaded, and executed by the virtual machine.

22. JVM runtime memory

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

23. Cenozoic Era

It’s used to store new objects. It takes up about a third of the heap. Because objects are created frequently, MinorGC is frequently triggered for garbage collection by the new generation. The Cenozoic era is divided into three regions: Eden, ServivorFrom and ServivorTo.

Eden area

Birthplace of a new Java object (if the newly created object takes up a lot of memory, it is allocated directly to the old age). When Eden runs out of memory, MinorGC is triggered to do a garbage collection for the new generation.

ServivorFrom

The survivor of the last GC, as the scanned for this GC.

ServivorTo

A MinorGC survivor was saved.

MinorGC process (copy -> empty -> swap)

MinorGC uses a copy algorithm.

(1) Copy Eden and servicorFrom to ServicorTo, age +1

First, copy the surviving objects in Eden and ServivorFrom to the ServicorTo region (if there are any objects whose ages meet the criteria of old age, the value is assigned to the old age region), and at the same time, add the age of these objects +1 (if ServicorTo is not enough, put it into the old age region).

(2) Clear Eden and servicorFrom

Then, empty the objects in Eden and ServicorFrom;

(3) ServicorTo and ServicorFrom are exchanged

Finally, the ServicorTo and ServicorFrom are swapped, and the old ServicorTo becomes the ServicorFrom section for the next GC.

The old days

It mainly stores memory objects with long lifetime in application programs.

Older objects are more stable, so MajorGC is not executed very often. Before MajorGC is generally carried out a MinorGC, so that there is a new generation of objects into the old age, resulting in space is not enough time to trigger. MajorGC is also triggered early for garbage collection to free up space when a large contiguous space cannot be found for a newly created larger object.

MajorGC uses a mark-clearing algorithm: it scans all the ages once, marks the surviving objects, and then recycles the unmarked objects. AjorGC takes a long time because it is scanned and recycled. MajorGC generates memory fragmentation, and in order to reduce memory consumption, we usually need to merge or mark it for direct allocation next time. An OOM (Out of Memory) exception is raised when the old age is too full.

Permanent generation

A permanent area of memory where classes and Meta information are stored. Classes are placed in a permanent area when they are loaded. Unlike the area where instances are stored,GC does not clean the permanent area during the main program runtime. This also causes the permanent generation area to swell as more classes are loaded, resulting in an OOM exception.

JAVA8 and metadata

In Java8, the persistent generation has been removed and replaced by an area called the “metadata area” (meta space). The essence of a meta-space is similar to that of a permanent generation. The biggest difference between a meta-space and a permanent generation is that the meta-space does not exist in a VIRTUAL machine but uses local memory. Therefore, by default, the size of the meta-space is limited only by local memory. The class’s metadata is put into NativemEmory, and the string pool and static variables of the class are put into the Java heap, so that the amount of class metadata that can be loaded is controlled not 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 do so by reference. Therefore, it is obvious that a simple way to determine whether an object is recyclable is by reference counting. Simply put, an object that has no references associated with it, that is, none of them has a reference count of zero, which means that the object is unlikely to be used again, and therefore is a recyclable object.

28. Accessibility analysis

To solve the circular reference problem of reference counting, Java uses the method of reachability analysis. Search through a series of “GC Roots” objects as a starting point. If there is no reachable path between “GC roots” and an object, the object is said to be unreachable. It is important to note that unreachable objects are not equivalent to recyclable objects, and at least two marking processes are required for unreachable objects to become recyclable. If the object is still recyclable after two marks, it will face collection.

29. Mark-sweep algorithm

The most basic garbage collection algorithm is divided into two stages, annotation and cleanup. The mark phase marks all objects that need to be reclaimed, and the clear phase recycles the space occupied by the marked objects. As shown in figure

As can be seen from the figure, the biggest problem of this algorithm is the serious memory fragmentation, and the problem that large objects cannot find available space may occur later.

30. Copying Algorithms

An algorithm was proposed to solve the memory fragmentation defect of Mark-Sweep algorithm. The memory is divided into two pieces of equal size based on the memory capacity. Use only one block at a time. When this block is full, copy the surviving objects to the other block to clear the used memory, as shown in the figure:

Although this algorithm is simple to implement, has high memory efficiency and is not easy to generate fragmentation, the biggest problem is that the available memory is compressed to half of the original. Also, with more surviving objects, the efficiency of Copying algorithms decreases dramatically.

31. Mark-compact Algorithm

Combined with the above two algorithms, in order to avoid defects. The marking phase is the same as the Mark-sweep algorithm. Instead of cleaning up objects, the living objects are moved to one end of memory. It then clears objects outside the end boundary. As shown in figure:

32. Generational collection algorithm

Generational collection is the current approach used by most JVMS. The core idea is to divide memory into different domains based on the lifetime of an object, typically dividing the GC heap into Tenured/Old Generation and YoungGeneration. The characteristics of the old generation are that only a small number of objects need to be recycled in each garbage collection, while the characteristics of the new generation are that a large number of garbage needs to be recycled in each garbage collection, so different algorithms can be selected according to different regions.

New generation and replication algorithm

Most JVM GCS currently adopt a Copying algorithm for the new generation because it recycles most of its objects with each garbage collection, meaning there are fewer operations to copy, but the new generation is not usually classified in a 1:1 fashion. Generally, the new generation is divided into a large Eden Space and two small Survivor Spaces (From Space, To Space). Each time Eden Space and one Survivor Space are used, when recycling, The surviving objects in the two Spaces are copied to the other Survivor space.

34, old age and tag copy algorithm

In the old days, the mark-Compact algorithm was used because only a few objects were collected at a time.

(1) Permanet Generation, which is used to store class classes, constants, method descriptions, etc. Recycling of the immortal generation mainly involves discarding 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 Survivor Space(Survivor currently storing objects), and in a few cases, it will be directly allocated to the old generation.

(3) When the EdenSpace and From Space of the new generation are insufficient, a GC will occur. After GC, the surviving objects in EdenSpace and From Space will be moved To To Space. Then clean up Eden Space and FromSpace.

(4) If To Space is not enough To store an object, the object is stored in the old generation.

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

(6) When an object escapes a GC on Survivor, its age is +1. By default, objects aged 15 are moved to the old generation.

JAVA strong references

The most common in Java is strong references, where an object is assigned to a reference variable that is a strong reference. When an object is referenced by a strongly referenced variable, it is in a reachable state and cannot be collected by the garbage collection mechanism, even if the object will never be used or collected by the JVM. So strong references are one of the main causes of Java memory leaks.

JAVA soft references

A SoftReference is delivered using the SoftReference class. An object with only a SoftReference is not reclaimed when the system memory is sufficient, but is reclaimed when the system memory is insufficient. Soft references are usually used in memory-sensitive programs.

37. JAVA weak references

WeakReference needs to be realized by WeakReference class, which has a shorter lifetime than soft reference. For objects with only weak references, as long as the garbage collection mechanism runs, regardless of whether the memory space of JVM is enough, it will always reclaim the memory occupied by the object.

JAVA virtual references

Virtual references need to be implemented by the PhantomReference class, which cannot be used alone but must be used in conjunction with the reference queue. The main purpose of a virtual reference is to track the status of an object being garbage collected.

Generation collection algorithm

The current mainstream VM garbage Collection uses “Generational Collection,” which divides memory into chunks based on the lifetime of an object, such as the new generation, the old generation, the permanent generation in the JVM, In this way, the most appropriate GC algorithm can be used according to the characteristics of each era

In the new generation – replication algorithm

Each garbage collection finds a large number of objects dead and only a few alive. Therefore, the selection of replication algorithm, only need to pay a small amount of replication cost of living objects can complete the collection

In the old days – tag sorting algorithm

Because the object has a high survival rate and no extra space is guaranteed to allocate it, a “mark-clean” or “mark-tidy” algorithm must be used to recycle it without memory replication and free memory directly.

Partition collection algorithm

Partition algorithm divides the whole heap space into continuous different cells, and each cell is used independently and recycled independently. The advantage of this is that you can control how many cells are recycled at a time, and reasonably recycle several cells at a time (rather than the whole heap) depending on the target pause time, thereby reducing the pauses generated by a SINGLE GC.

The GC garbage collector

Java heap memory is divided into the new generation and the old generation. The new generation mainly uses copy and mark-clean garbage collection algorithms. The older generation mainly uses mark-sort garbage collection algorithms, so there are several different garbage collectors in the Java virtual machine for the new generation and the older generation respectively. In JDK1.6, the Sun HotSpot VIRTUAL machine has the following garbage collector:

Serial garbage collector (single thread, replication algorithm)

Serial is a basic garbage collector that uses a replication algorithm and was the only garbage collector in the new generation prior to JDK1.3.1. Serial is a single-threaded collector that not only uses one CPU or one thread to complete garbage collection, but must suspend all other worker threads until the garbage collection is complete.

The Serial garbage collector, while suspending all other worker threads during garbage collection, is simple and efficient, achieving the highest single-thread garbage collection efficiency for a limited single-CPU environment without the overhead of thread interaction. So Serial garbage collector is still the default generation garbage collector for Java virtual machines running in Client mode.

45, ParNew garbage collector (Serial+ Multithreading)

The ParNew garbage collector is a multithreaded version of the Serial garbage collector. It also uses a replication algorithm and behaves exactly the same as the Serial garbage collector except that it uses multiple threads for garbage collection. The ParNew garbage collector also suspends all other worker threads during garbage collection.

By default, the ParNew collector opens the same number of threads as the number of cpus. You can limit the number of garbage collector threads by using the -xx :ParallelGCThreads parameter. 【Parallel 】

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

49, Parallel Avenge (Multi-threaded replication algorithm, efficient)

The Parallel Scavenge collector is a new generation garbage collector that also uses replication algorithms and is a multi-threaded garbage collector that focuses on achieving a controlled throughput (Thoughput, the amount of time the CPU takes to run user code, 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. Adaptive conditioning strategies are also an important difference between the ParallelScavenge collector and the ParNew collector.

Serial Old collector

Serial Old is the older version of the Serial garbage collector, which is also a single-threaded collector using the mark-collation algorithm. This collector also runs mainly on the Client default

The default generation garbage collector for the Java virtual machine. In Server mode, there are two main uses:

To be used with the new generation Parallel exploder in versions prior to JDK1.5.

(2) As a backup garbage collection solution for the older generation using the CMS collector. Garbage collection process diagram of new Generation Serial and Old generation Serial

The next-generation Parallel Scavenge collector is similar to the ParNew collector in that it is a multi-threaded collector and uses replication algorithms to suspend all worker threads during garbage collection. Avenge the insane and ParNew insane.

Parallel Old collector (Multi-thread tag collation Algorithm)

The Parallel Old collector is an older version of the Parallel insane, using the multithreaded mark-collation algorithm and was only available in JDK1.6.

Insane insane Insane Insane Insane Insane Insane Insane Insane insane insane insane insane insane insane The Parallel Old collector is designed to provide a through-first garbage collector in the older generation. The Newer Generation Parallel Scavenge and the Older Generation Parallel Old collector can be used as a match strategy if the system requires higher throughput.

Insane and older Generation Parallel collector

49, CMS collector (multi-threaded tag clearing algorithm)

A Concurrent Mark sweep(CMS) collector is an tenured garbage collector whose primary goal is to obtain the minimum garbage collection pause time. Unlike other tenured mark-collation algorithms, it uses a multithreaded mark-sweep algorithm. Minimum garbage collection pauses can improve the user experience for highly interactive applications. The CMS mechanism is more complex than other garbage collectors. The whole process is divided into the following four stages:

Initial tag

Just mark objects that GC Roots can associate directly, which is fast, and still suspend all worker threads.

Concurrent tags

The process of GC Roots tracing, which works with the user thread without the need to suspend the worker thread.

To mark

All worker threads still need to be suspended in order to correct the mark record for the part of the object whose mark changes as the user program continues to run during concurrent marking.

Concurrent remove

Remove unreachable GC Roots objects and work with the user thread without suspending the worker thread. Since the garbage collector thread can now work concurrently with the user during the longest concurrent marking and concurrent cleaning processes, the CMS collector’s memory collection and the user thread are generally executed concurrently. CMS collector working process

G1 collector

Garbage First Garbage collector is the most advanced theoretical development of Garbage collector. Compared with CMS collector, G1 collector has two most prominent improvements:

(1) Based on mark-collation algorithm, no memory fragmentation is generated.

(2) Pause time can be controlled very precisely, and low pause garbage collection can be achieved without sacrificing throughput. The G1 collector avoids region-wide garbage collection by dividing heap memory into separate regions of fixed size and tracking the progress of garbage collection in these regions, while maintaining a priority list in the background that prioritizes the areas with the most garbage collected at a time based on the allowed collection time. Zone partitioning and priority zone collection mechanisms ensure that the G1 collector can achieve maximum garbage collection efficiency in limited time

Class loading mechanism

51, JVM class loading mechanism

The JVM class loading mechanism is divided into five parts: loading, validation, preparation, parsing, and initialization. Let’s take a look at each of these five processes.

loading

Loading is the phase of the Class loading process that generates a java.lang.Class object in memory that represents the Class and acts as an entry point to the Class’s various data in the method area. Note that this does not have to be obtained from a Class file; it can be read from ZIP packages (such as JAR packages and WAR packages), computed at runtime (dynamic proxies), or generated from other files (such as JSP files converted to the corresponding Class classes).

validation

The main purpose of this phase is to ensure that the byte stream in the Class file meets the requirements of the current virtual machine and does not compromise the security of the virtual machine.

To prepare

The preparation phase is the formal allocation of memory for class variables and the setting of initial values for class variables, that is, the memory space used by the allocation of these variables in the method area. Note the concept of initial values here, such as a class variable defined as:

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 the statement is:

public static final int v = 8080;
Copy the code

The ConstantValue attribute is generated for V during compilation, and the virtual machine assigns v a value of 8080 based on the ConstantValue attribute during preparation.

parsing

The parsing phase is the process by 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;
Copy the code

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 the statement is:

The ConstantValue attribute is generated for V during compilation, and the virtual machine assigns v a value of 8080 based on the ConstantValue attribute during preparation.

parsing

The parsing phase is the process by 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;
Copy the code

The ConstantValue attribute is generated for V during compilation, and the virtual machine assigns v a value of 8080 based on the ConstantValue attribute during preparation.

parsing

The parsing phase is the process by which the virtual machine replaces symbolic references in the constant pool with direct references. Symbolic references are in the class file:

(1) CONSTANT_Class_info

(2) CONSTANT_Field_info

(3) the CONSTANT_Method_info

Constants of the same type.

Symbolic reference

Symbolic references are independent of the layout implemented by the virtual machine, and the target of the reference does not have to have been loaded into memory. The memory layout of various virtual machine implementations can vary, but the symbolic references they accept must be consistent, because the literal form of symbolic references is explicitly defined in the Class file format of the Java Virtual Machine specification.

Direct reference

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

Initialize the

The initialization phase is the last phase of class loading, and after the previous class loading phase, all operations are dominated by the JVM, except that the class loader can be customized during the loading phase. In the inception phase, you actually execute the Java program code defined in the class.

Class constructor

The initialization phase is the process of executing the class constructor methods. Methods are a combination of assignment operations that the compiler automatically collects for class variables in a class and statements in a static statement block. The virtual machine guarantees that the parent method will execute before the child method executes. The compiler may not generate () methods for a class that has no static variable assignments and no static statement blocks. Note that class initialization is not performed in the following cases:

(1) A reference to a static field of a parent class by a subclass will trigger the initialization of the parent class, not the subclass.

(2) Define an array of objects that will not trigger initialization of the class.

(3) Constants are stored in the constant pool of the calling class during compilation. In essence, there is no direct reference to the class in which the constant is defined, and the class in which the constant is defined is not triggered.

(4) Fetching a Class object by its name does not trigger Class initialization.

If initialize is false, Class initialization is not triggered. This parameter tells the vm whether to initialize the Class.

(6) The default loadClass method of ClassLoader will not trigger the initialization action.

Class loaders

The virtual machine design team put the loading action outside the JVM implementation to let the application decide how to get the required classes, and the JVM provides three types of loaders:

Bootstrap ClassLoader

Classes that are 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 (by filename, such as rt.jar).

Extension ClassLoader

Is responsible for loading class libraries 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’s classpath. The JVM loads classes through the parent delegate model, but we can also implement custom class loaders by inheriting java.lang.ClassLoader.

Parent assignment

When a class receives a classload request, it first does not attempt to load the class itself. Instead, it delegates the request to the parent class. This is true of every hierarchical classloader, so all load requests should be passed to the starting classload. The subclass loader will try to load the request itself only if the parent Class loader reports that it is unable to complete the request (the desired Class is not found in its load path).

One advantage of using parental delegation is that, for example, loading the java.lang.Object class in the rt.jar package, whichever loader loads the class ends up delegating to the top bootstrap class loader, thus ensuring that different classloaders will end up with the same Object

54. OSGI (Dynamic Modeling System)

OSGi(Open Service Gateway Initiative) is a dynamic model system for Java. It is a series of specifications for Java dynamic modular system.

Dynamically changing the structure

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

Modular programming and hot swap

OSGi is designed to provide the foundation for modular programming of Java programs. Osgi-based programs are likely to be hot-pluggable at the module level. When an application is updated, it can be deactivated, re-installed, and then launched as part of a program, which is a very attractive feature for enterprise development.

OSGi describes a beautiful modular development goal, defines the services and architectures needed to achieve it, and has a mature framework to support it. But not all applications are suited to OSGi as an infrastructure. While it provides power, it introduces additional complexity because it does not adhere to the parent-delegate model of class loading.

57, JVM memory model

Thread-exclusive: stacks, local method stacks, program counters

Thread sharing: heap, method area

58, stack

Also known as method stack, thread private, thread execution method is to create a stack array, used to store local variable table, operation stack, dynamic link, method exit information. A method is pushed when called, and a method is pulled back from the stack.

59. Local method stack

Similar to a stack, it is used to hold information about the execution method. Java methods are executed using the stack, while Native methods are executed using the local method stack.

60. Program counter

It stores the bytecode position executed by the current thread. Each thread has an independent counter when working, which only serves for executing Java methods. When executing Native methods, the program counter is empty.

61, heap

The largest portion of JVM memory management, shared by threads, is intended to hold object instances. Almost any object instance will be placed here, and an OOM exception will be raised when the heap runs out of space. Depending on the lifetime of the object, the JVM manages the object by generation, and the garbage collector manages the garbage

62. Method area

Also known as the non-heap area, it is used to store information about classes that have been loaded by the virtual machine, constants, static variables, code optimized by the just-in-time compiler, etc. The permanent generation of 1.7 and the metadata space of 1.8 are both implementations of the method area.

Generation recycling

Generational recycling is based on two facts: most objects are soon out of use, and some are not immediately useless, but do not last very long

Young generation -> mark – copy

Old age -> mark – clear

The difference between heap and stack

A stack is a run-time unit that represents logic and contains basic data types and references to objects in the heap in a contiguous area without fragmentation. A heap is a unit of storage that represents data that can be shared by multiple stacks (including basic data types, references, and reference objects in members) in a discontiguous area that can be fragmented.

(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 a member variable, local variable, or class variable, the object they point to is stored in heap memory.

(2) sharing is different

Stack memory is thread private.

Heap memory is common to all threads.

(3) Different abnormal errors

An exception is thrown if the stack or heap is out of memory.

There is insufficient space on the stack: Java. Lang. StackOverFlowError.

There is insufficient space on the heap: Java. Lang. OutOfMemoryError.

(4) Space size

The stack size is much smaller than the heap size

65, When will FullGC trigger

In addition to a direct call to System.gc, Full GC execution can be triggered in four ways.

(1) Insufficient space in the old generation

The old generation space is insufficient only when the new generation object is rolled in and created as a large object or array. If the old generation space is still insufficient after the Full GC, the following error is raised

Error:

java.lang.OutOfMemoryError: Java heap space

To avoid FullGC caused by these two conditions, you should try to tune so that objects are collected during the Minor GC phase, keep objects alive longer in the new generation, and don’t create objects and arrays that are too large.

(2) The Permanet Generation space is used up

PermanetGeneration stores information about some classes, etc. When there are too many classes to load, reflected classes, and called methods in the system, the PermanetGeneration may be occupied and will perform Full GC if it is not configured to use CMS GC. If the Full GC fails, the JVM throws the following error message:

java.lang.OutOfMemoryError: PermGen space

To avoid Full GC, increase the Perm Gen space or switch to CMS GC.

(3) Promotion failed and Concurrent mode failure occur during CMS GC

For programs that use CMS for legacy GC, pay particular attention to the presence of promotion failed and Concurrent mode failure in the GC logs, which may trigger Full GC.

Promotionfailed is caused by a Minor GC in which survivor Spaces are not available and objects can only be placed in older generations. Concurrentmode Failure is caused by running out of space in the old generation while an object is being put into the old generation during the CMS GC.

The countermeasures are: increase survivorspace, older generation space, or lower the ratio of triggering concurrent GC, but in JDK 5.0+, 6.0+ version, it may be due to JDK bug29 that CMS can trigger the jie action long after the remark is finished. For this kind of situation, can be set up through – XX: CMSMaxAbortablePrecleanTime = 5 (in ms) to avoid.

(4) The average size of Minor GC promoted to the old generation is larger than the remaining space of the old generation

This is a complicated trigger case, so Hotspot does a Minor GC to avoid running out of space in the old generation because the new generation object is promoted to the old generation. If the average size of the Minor GC promoted to the old generation is greater than the remaining space in the old generation, Then trigger the Full GC directly.

For example, if a 6MB object is promoted to the old generation after MinorGC is triggered for the first time, the next MinorGC will check to see if the old generation has more than 6MB free space, and if it is less than 6MB, Full GC will be performed.

When the new generation uses PSGC, the method is slightly different. The PSGC checks after the first Minor GC. For example, after the first Minor GC, the PSGC checks if the remaining space of the old generation is greater than 6MB. In addition to the above four cases, Sun JDK applications that use RMI for RPC or administration perform Full GC once an hour by default. May be passed by at startup – Java – Dsun. Rmi. DGC. Client. GcInterval = 3600000 to set up the Full GC execution time interval or through – XX: + DisableExplicitGC to prohibit rmi System. GC

What is a Java Virtual machine? Why is Java called a “platform independent programming language”?

A 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 them individually for each platform. The Java virtual machine makes this possible because it knows the instruction length and other features of the underlying hardware platform.

67. Object allocation rules

(1) Objects are allocated in Eden area first. If Eden area does not have enough space, the VM performs 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 Eden region and two Survivor regions (the new generation uses a replication algorithm to collect memory).

(3) The object of long-term survival enters the old age. The virtual machine defines an age counter for each object. If the object passes one Minor GC, the object enters the Survivor zone. After each Minor GC, the age of the object increases by one until the object reaches the threshold and enters the old zone.

(4) Dynamically judge the age of the object. If the sum of the size of all objects of the same age in the Survivor zone is greater than half of the Survivor space, objects older than or equal to that age can go straight to the old age.

(5) Guarantee of space allocation. Each time a Minor GC is performed, the JVM calculates the average size of an object that has been moved from Survivor to old, performs a Full GC if this value is greater than the size of the remaining value of the old, and checks HandlePromotionFailure if it is smaller, If true, only Monitor GC is performed, and if false, Full GC is performed

Describe how the JVM loads class files.

The loading of classes in the JVM is implemented by the ClassLoader and its subclasses. The ClassLoader in Java is an important component of the Java runtime system that finds and loads classes in class files at runtime.

Because of Java’s cross-platform nature, a compiled Java source program is not an executable program, but one or more class files. When a Java program needs to use a class, the JVM ensures that the class has been loaded, wired (validated, prepared, and parsed), and initialized.

Loading a class refers to reading the data from the class’s.class file into memory, usually by creating a byte array that reads into the.class file and generates a class object corresponding to the loaded class. After loading, the Class object is not complete, so the Class is not available at this point.

When the class is loaded, it enters the connect phase, which consists of three steps: validation, preparation (allocating memory for static variables and setting default initial values), and parsing (replacing symbolic references with direct references). Finally, the JVM initializes the class,

Include:

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

(2) If there are initialization statements in the class, execute those initialization statements in turn. The loading of classes is done by class loaders, including the root loader (BootStrap), Extension loader (Extension), System loader (System), and user-defined ClassLoader (a subclass of java.lang.classloader).

Since Java 2 (JDK 1.2), the class loading process has adopted the parent delegate mechanism (PDM). PDM ensures the security of the Java platform. In this mechanism, the Bootstrap of the JVM is the root loader, while all other loaders have one or only one parent class loader. The loading of a class is first requested by the parent class loader, and only when the parent class loader is unable to do so is the subclass loader loaded by itself. The JVM does not provide a reference to Bootstrap to a Java program. The following is a description of several class loaders

Bootstrap: Generally implemented in native code, responsible for loading the JVM base core libraries (rt.jar).

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

System: also called application class loader, its parent 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 of a user-defined loader.

Java object creation process

(1) When the JVM encounters an instruction to create an object, it first checks whether the instruction’s parameters can be defined as symbolic references to a class in the constant pool. Then load the class (class loading is covered later)

(2) Allocate memory for objects. One is “pointer collision”, another is “free list”, and finally the most common method is “Local Thread buffer allocation (TLAB)”.

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

(4) Set the object header as necessary

70, Briefly describe the Java object structure

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

The object header consists of two parts. The first part stores the runtime data of the object itself: hash code, GC generation age, lock identifier status, thread held locks, and biased thread ID (typically 32/64 bits). The second part is the pointer type, which points to the object’s class metadata type (that is, which class the object represents). In the case of an array object, a portion of the object header is used to record the length of the array.

Instance data is used to store the actual valid information of the object (both inherited from the parent class and defined by itself)

Aligned padding: The JVM requires that the object’s starting address be an integer multiple of 8 bytes (8-byte alignment)

71, how to determine the object can be recycled

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

Reference count: Each object has a reference count property. When a new reference is added, the count is increased by 1. When a reference is released, the count is decreased by 1. This method is simple and does not solve the problem of objects referring to each other circularly.

Reachability Analysis: Start with GC Roots and search down the path called the reference chain. When an object is not connected to GC Roots by any reference chain, the object is unusable and unreachable.

Does garbage collection occur in permanent generations of the JVM

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. If you look closely at the output from the garbage collector, you will see that persistent generations are also collected. This is why the correct permanent generation size is important to avoid Full GC. See Java8: From permanent generation to metadata.

73. Garbage collection algorithms

There are three basic GC algorithms: mark-clean algorithm, copy algorithm, and mark-compression algorithm. Our common garbage collectors generally adopt generational collection algorithm.

Mark-clear algorithm

The Mark-sweep algorithm, as its name suggests, is divided into two phases: “Mark” and “Sweep.” It flags all objects that need to be reclaimed, and when it’s done, it dumps all of the flagged objects.

Replication algorithm

A collection algorithm for “Copying” that divides available memory into two equivalent pieces by capacity and uses only one piece at a time. When this area of memory is used up, the surviving objects are copied to the other area, and the used memory space is cleaned up again.

Mark-compression algorithm

The marking process is still the same as the mark-clean algorithm, but instead of cleaning up the recyclable objects directly, the next step is to move all surviving objects toward one end and then clean up memory directly beyond the end boundary

Generational collection algorithm

A “Generational Collection” algorithm divides the Java heap into Generational and older generations so that the most appropriate Collection algorithm can be used for each generation

Tuning the

What are the tuning commands?

The Sun JDK monitoring and troubleshooting commands are 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 used to monitor the virtual machine running status information, it can display the virtual machine process class loading, memory, garbage collection, JIT compilation and other running data.

(3) Jmap, JVM Memory Map command is used to generate heap dump file

Jhat JVM Heap Analysis Tool jHAT JVM Heap Analysis Tool jHAT JVM Heap Analysis Tool jHAT JVM Heap Analysis Tool jHAT JVM Heap Analysis Tool jHAT JVM Heap Analysis Tool jHAT JVM Heap Analysis Tool

(5) JStack, which is used to generate the thread snapshot of the Java VIRTUAL machine at the current time.

(6) Jinfo, JVM Configuration info This command is used to view and adjust vm running parameters in real time

Tuning tools

Common tuning tools are divided into two categories. The JDK comes with monitoring tools: JConsole and JVisualVM, and the third parties are: MAT(Memory AnalyzerTool) and GChisto.

Java Monitoring and Management Console (JConsole) is a Java Java Monitoring and Management Console (JDK) that monitors memory, threads, and classes in the JVM

(2) JVisualVM, JDK with omnipotent tools, can analyze memory snapshot, thread snapshot; Monitor memory changes, GC changes, etc.

(3) MAT, the 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 to analyze GC logs

When will Minor and Full GC occur?

MGC, also known as YGC, occurs when the JVM runs out of memory

77. You know what JVM performance tuning is

Set the heap memory size

-Xmx: indicates the maximum heap memory limit.

Set the Cenozoic size. The new generation should not be too small, otherwise there will be a flood of objects into the old age

-xx :NewSize: indicates the size of the new generation

-xx: Proportion of Cenozoic and old NewRatio

-xx :SurvivorRatio: ratio of Eden space and survivor space

Set the garbage collector to the young substitute -xx :+UseParNewGC the old substitute -xx :+UseConcMarkSweepGC

conclusion

Some Spring Cloud and Docker microservices architecture practice more than 270 pages of information collection, Java virtual machine: JVM Advanced Features and Best Practices Study Notes 400 pages PDF summary, and Spring Family (1187 pages PDF), 1000 questions for Java engineers interview, focus on the public: Qilin bug.