Same old rule — like first, bookmark later

Memory partition

How is the memory region of the JVM divided? And explain the role of each given region.

  • Program counters (private) : Simple to understand as line numbers. The bytecode interpreter works by looking for the next bytecode instruction through the program counter.
  • Virtual stack (private) : Describes the memory model of Java method execution. Each method execution creates a stack frame for storing local variables, operand stacks, dynamic links, method exits, and so on.

The virtual stack is the model that describes the method, so think about what the method has for easy memorization.

    public int Hello(int x){ 
        int a=1,b=1; # A, B, and X are all placed in the local variable tableintc=a+b; # + getHello(); The target method being called cannot be determined at compile time. Symbolic references can only be converted from the runtime constant pool into direct references, a process known as dynamic linking.returnc; This return is the exit of the method. }Copy the code
  • Native method stack (private) : The virtual machine stack serves the same purpose, except that the virtual machine stack serves the Java methods, while the Native method stack serves the Native methods invoked by the virtual machine.
  • Heap (shared) : The largest chunk of memory in the Java virtual machine, shared by all threads, where almost all object instances allocate memory.
  • Method area (shared) : Used to store information about classes that have been loaded by the virtual machine, constants, static variables, just-in-time compiled code (jIT-generated symbolic references are placed in the runtime constant pool), and so on.

How is the JVM heap memory divided internally?

The heap is divided into young generation and old generation. The young generation is divided into Eden region and Survivor region. Survivor is divided into From and To region. eden:from:to=8:1:1

What are the differences between method region, permanent generation, and metacolor?

The method area is the JVM memory specification, and the persistent generation is the JVM implementation of this specification. Metaspaces are an implementation that replaced permanent generations after 1.8. And only HotSpot has persistent generation.

Why do you use a meta-space instead of a permanent generation?

Because there is a permanent MAX cap, it is easy to run into memory overflow problems. The most typical scenario is that in the case of a large number of JSP pages, it is easy to run out of permanent generation memory. Therefore, after 1.8, metaclass is used instead of permanent generation. Metaclass uses local memory. As long as the local memory is large enough, oom problem can be solved.

What is the difference between a deep copy and a shallow copy?

Shallow copy: adds a pointer to an existing memory address. Deep copy: adds a pointer to a new memory and makes the added pointer point to the new memory

Class loading mechanism

How does a Java class work?

Java classes are first coded into.class files using the packaging tool. The JVM then loads the.class file into memory through the classloader, and eventually the JVM executes the classes loaded into memory that we’ve written, based on its bytecode execution engine.

Talk about the loading process of JVM classes

Load – link – Initializing links include: Verify -> Prepare -> parse

Can you explain exactly what each step does?

  • Load: Loads the class file into memory.
  • Validation: Verify that your.class files are in compliance with relevant specifications.
  • Preparation: Allocate memory space for corresponding classes and variables, and assign initial values.
  • Parsing: Symbolic references become direct references. (What is symbolic reference is explained in the dynamic linking section of memory swap.)
  • Initialization: Actually executes the Java program code defined in the class. This includes operations such as logical handling of assignments.

When is a class initialized?

  1. When executing Java virtual machine directives (new, getStatic, putstatic, Invokestatic) that need to reference a class or interface
  2. Call some reflection method in the class library.
  3. Initialize a child class. If the parent class is not initialized, the parent class is initialized first.
  4. The main class, which contains the “main()” method, is initialized immediately.

How many class loaders are there in Java?

  1. Bootstrap ClassLoader: loads the core classes in the Java directory. In the JDK installation directory, there is a lib directory, which is the core Java class library. Starting the class loader is loading the classes down here.
  2. Extension ClassLoader: This is similar to the start ClassLoader, except that it loads classes in the lib/ext directory.
  3. The Application ClassLoader is used to load your own classes according to your needs
  4. Custom class loaders: This is nothing but your custom class loaders.

Why do you need a custom classloader?

Java code is known to be easily decompiled, so if you need to encrypt your code to prevent decompilation, this is where custom classloaders come in.

What is the parent delegate loading mechanism?

Hello. Class, when it’s loaded into memory, it will ask its dad — extension classloader, and then the extension classloader will ask its dad — start classloader, and then the startup classloader will start looking for Hello.class in lib, and if it doesn’t find it, it’ll tell the extension classloader, “Go play,” I don’t have any. Extension class a see dad didn’t have that I come, look for a long time he also didn’t, and then tell the application class loader said me and your grandpa can’t help you, you have to rely on yourself to find. This process is called parental delegation.

What is the role of parental delegation?

  1. Security: Prevents core classes from being tampered with. For example, if you define a java.lang.String class, it will not load the class when it finds that the parent class loader is already loaded.
  2. Avoid reloading: The child loader will not load classes that have already been loaded by the parent loader, effectively preventing reloading problems.

An example of breaking parental delegation

  1. Design flaw, because the more basic classes are loaded by the upper loader, but if some of the basic classes call user code, this will break (SPI). You can guide to Dubble from this SPI if you know what dubble is.
  2. OSGI (hot deployment) due to user program dynamics.

Tomcat breaks the parent delegate instance

  • Tomcat is a Web container. Multiple programs can be deployed in a Web container. Different programs depend on different versions of the third-party class library. And libraries that the Tomcat container depends on and applications need to be isolated for security. This breaks the parental delegation.
  • It is well known that JSP files are also finally compiled into class files that are clipped to the virtual machine. For class modifications, if the class name is the same, the class loader will directly fetch the existing class in memory, and the modification will not take effect. Tomcat does not need to restart the service to modify the JSP page. It also breaks the parental delegation mechanism. How does Tomcat do that? He has a JSP classloader for each JSP. When the JSP changes, unload the classloader, recreate the classloader, and reload the JSP file.

The garbage collection

How do I determine if an object is garbage

  1. Reference count: Adds a reference counter to an object that is +1 when there is a reference and -1 when there is no reference. When this counter has a value of bit 0, the object is dead and can be reclaimed.

Disadvantages: This algorithm will appear circular reference (A-> B b->A) can not be recycled. 2. Reachability analysis: When an object has no reference to GCRoots, it indicates that the object is not available. For GCRoots, we can understand it as the local variable of method and static variable of class. The instance variable is not.

What are the four reference types?

  • Strong references: cannot be reclaimed at any time.
  • Soft reference: When memory is insufficient, it will be reclaimed. You can apply it to caching.
  • Weak references: will be collected in the next GC.
  • Virtual reference: also called ghost reference; Unable to obtain objects through virtual references, virtual references are implemented with PhantomReference, whose purpose is to return a notification at GC time.

Garbage collection algorithm

Mark clear

Mark useless objects and remove them altogether. Problems: ① efficiency problem, ② space utilization problem, prone to floating debris, when creating large objects will trigger garbage collection again.

copy

Copy: Divide memory into two pieces of equal size, use only one piece at a time, when memory is full, we copy the surviving pieces to the other piece, then delete the rest. Problems: Although the floating debris problem is solved, the efficiency of memory usage is reduced because only half of the memory is available at a time. And if the object memory is high, garbage collection will be triggered frequently.

Tag to sort out

Mark collation: Mark unwanted objects, move all surviving objects towards one end, and then clear memory directly beyond the end boundary. It is a good solution to the problem of floating debris removed by markers. The problem: Efficiency

Generational collection

The memory is divided into several blocks according to the different life cycle of the object, generally the new generation and the old age. The new generation basically adopts the copy algorithm, and the old age adopts the mark clearing algorithm.

Garbage collector

Serial and serial old

Single-threaded garbage collection, as the name suggests, is one for the new generation and one for the old. It is hardly used now.

parnew

Multithreaded garbage collector, which is in the new generation, is often used with CMS.

parallel

It is also called a “throughput-first collector” (throughput = code run time/code run time + garbage collection time). Low pause times can increase user experience and high throughput can improve CPU efficiency. It is also often used with CMS

cms

Use mark clearing algorithm, suitable for the old age. The four phases of a CMS:

  1. Initial tag: The tag is GCRoot, which stops the world.
  2. Concurrent marking: Start tracking all live objects through GCRoot, and this process will make the program work.
  3. Re-mark: Because the concurrent marking process is still running and generates some garbage, it needs to be re-marked. This process stops the world.
  4. Concurrent cleanup: Concurrent garbage cleanup.

The following side code is used as an example to explain:

public class Hello {
    private static A a = new A();
}
class A{
    private B b =new B();
}
class B{}
Copy the code

Disadvantages:

  • The disadvantage of tag clearing can produce suspended space debris
  • Consumes CPU resources. Concurrent cleanup and concurrent markup processes are CPU intensive. The default number of threads started by the CMS is (CPU core +3) /4. The default for 4G with 2 cores is one CPU.
  • A Concurrent Mode Failure occurs when a program is allowed to run during a Concurrent cleanup. If the program is minorGC again during cleanup and there is not enough free space for the elderly wait to store objects, a Concurrent Mode Failure will occur. The garbage collector is then forced back to the Serial Old collector.

G1

The G1 collector is a new collector provided by JDK7 that has been changed to the default garbage collection algorithm since JDK9. The G1 collector is implemented based on a “mark-de-clutter” algorithm, which means that no memory fragmentation occurs. G1 divides memory into regions of equal size. The default is 2048 sizes from 1 to 32MB.

G1 collection process

  • Initial tag: As with CMS, the initial tag is GCRoot, which also needs to stop the world
  • Concurrent concurrent: As with CMS, tracking live objects through GCRoot is slower, so it is performed concurrently, but it does not affect the normal operation of the system.
  • Final tag: Used to deal with junk objects that remain after the concurrency phase ends. stop the morld

Filter the collection: This step is the most critical, and it is what allows G1 to control the expected stop time of the collection. G1 is selectively recycled based on price and cost. (For example, it takes 1s to reclaim a region10M and 1ms to reclaim another 200m; He will definitely choose the one with the 200m.

ZGC

ZGC is a low-latency garbage collector released in JDK 11. Like G1, ZGC is based on Reigon, with almost all phases concurrent, whole heap scan, partial collection, and partial generation. If you can answer this question prove that you are sensitive to new knowledge. You are the one the interviewer is looking for. Because it’s a crash film, I won’t go into details.

Conditions for the object to live in the old era

  • After many attempts, minorGC failed to recycle them all. The default is 15 times to the old age. You can run -xx :MaxTenuringThreshold to change the value.
  • Big object directly into the old age; Through – XX: PretenureSizeThreshold set standards of large objects.
  • The value after minorGC is greater than the size of survivor. Go straight to the old days

  • Dynamic judgment: If the total size of a batch of objects in survivor zone is greater than 50% of that in survivor zone, those whose age is greater than or equal to this batch of objects will be moved to the old zone.

When the total number of ages 1+ 2+ n exceeds 50% of the Survivor zone, all ages above N are added to the old age group. The figure below will move all >=2 years old to the old age.Promotion old age understanding memory map

Talk about the process and algorithm of the new generation GC

The new generation of objects tend to live and die, so the replication algorithm is used. After the object is born in Eden area, minorGC will be triggered to move the surviving object to one of the survivor two Spaces when it cannot bear the load. In the next GC, this space will be reclaimed together with Eden and the surviving object will be moved to a space. Since the default Eden :from:to=8:1:1, the later 10% space limit also greatly solves the space waste problem of the replication algorithm.

What is space allocation guarantee

Before Minor GC occurs, the virtual machine checks to see if the maximum contigual space available for the old generation is greater than the total space for all objects of the new generation, and if it is greater than the total space for all objects of the new generation, and if it is smaller than the virtual machine checks to see if the HandlePromotionFailure setting allows guarantee failure. If HandlePromotionFailure=true, it continues to check if the maximum contiguous available space of the old age is greater than the average size of the objects promoted to the old age, and if so, a Minor GC is attempted, but this Minor GC is still risky; This process guarantees space allocation. HandlePromotionFailure was removed after JDk1.6.

FullGC trigger time

Once the space guarantee parameter is removed we don’t have to worry about space guarantee anymore.

  • Memory The available memory in the old age is smaller than the average object size in the old age after the previous generation GC
  • If there are more survivors than survivors after the Minor GC in the new generation, then the old generation is out of memory
  • – XX: CMSInitiatingOccupancyFaction parameter, use the old s memory is beyond the proportion of this parameter will also trigger automatically.

The JVM tuning

Tuning tool

jps

You can view the process number. JPS -v displays running parameters.

jstat

Jstat Collects gc information. Parameter Description Value jstat -gcutil Indicates the process ID

jinfo

View virtual parameters; You can also adjust VM parameters.

jmap

Memory snapshot (you can also obtain a snapshot by setting VM parameters.) jmap-dump :format=b,file=d:\aa.bin pid

jhat

Snapshot analysis tool, which consumes a lot of CPU, generally we will generate a snapshot in the local analysis;

jstack

Stack monitoring for threads. The current thread call stack (also called threaddump) can be used to analyze deadlocks, loops, and requests for external resources to wait for a long time.

Jconsole, visual vm

Graphical JVM tuning tool.

Tuning parameters

  • -Xms Initializes the minimum allocated memory.
  • -Xmx Maximum allocated memory;
  • -xmn Sets the size of the young generation.
  • -Xss sets the stack size for each thread
  • -xx :NewRatio=2 The ratio of the young generation to the old generation is 1:2
  • -xx :SurvivorRatio=8 Ratio of Eden to survivor 8:2
  • -xx :+PrintGCDetails: Prints GC details.
  • -xx :+UseParNewGC opens the ParNew collector
  • XX: + UseConcMarkSweepGC open CMS
  • – XX: PretenureSizeThreshold promotion old s large object boundaries
  • -xx :MaxTenuringThreshold Specifies the threshold for the object to proceed to the old age

How to configure the project parameters of your company?

Different projects are different. You can check your company’s configuration by jPS-V and memorize it.

Common scenario analysis questions

There’s a lot of stalling on the line

First of all, we have to be slow to SQL; Enable slow query logs to view the SQL execution time. Then consider whether it is a garbage collection cooker and check for frequent fullGC through the memory monitoring tool. If fullGC is the cause, the solution is to replace the garbage collector, deploy multiple applications and redirect proxy through Nginx.

How to solve the problem of OOM appearing online

First line problem should think of some way to get programs are available, first to think of a solution, because the user is waiting for you there, affects their is god, are generally not load balance of the project, can oom first shut down the machine, but also consider some regular tasks at this time, news of consumption, Whether the rest of the machine can resist wandering ah and other problems. Then analyze the OOM cause, generate the Heapdump file through JMAP, and take the file from online to local Eclipse Memory Analyzer(MAT) for analysis.

Finally read don’t hurry to go to a concern, refuse white piao start from me.