• thinking
    • Please talk about your understanding of JVM. What are the updates for Java8 virtual machines?
    • OOM is what? What is StackOverflowError? What are the methods of analysis?
    • What do you know about common JVM parameter tuning?
    • Talk about what you know about classloaders in the JVM

JVM architecture

The JVM position

  • The JVM runs on top of the operating system and has no direct interaction with the hardware

Overview of THE JVM architecture

ClassLoader ClassLoader

Introduction to the

  • The class file is labeled at the beginning of the file, loads the bytecode content of the class file into memory, converts that content into a runtime data structure in the method area, and the ClassLoader is only responsible for loading the class file. Whether it can run or not, It’s up to the Execution Engine

  • The Car. Class bytecode file is loaded and initialized by the ClassLoader. A Car class template is generated in the method area. Conversely, we can perform getClass() on a specific instance and get the instance’s Class template, Car Class. Next, we perform getClassLoader() on the class template to see which class loader is loading the class template

  • The ClassLoader loads the class file, not only looking at the.class suffix of the file, but also checking whether there is a specific flag at the beginning of the file

Which class loaders are available

  • A built-in loader of the VM

    • Start the class loader (Bootstrap, C++), also called the root loader, and load %JAVAHOME%/jre/lib/rt.jar

      Rt: the Runtime

    • %JAVAHOME%/jre/lib/ext/*.jar

    • The AppClassLoader (written in Java), also known as the system classloader, loads all classes of %CLASSPATH%

  • User – defined loader

    • A subclass of java.lang. ClassLoader that allows you to customize how classes are loaded

Parent delegate and sandbox security

thinking

  • Take a look at these class loaders in the following code. GetParent () = null; getParent() = null; getParent() = null; Shouldn’t it be the Bootstrap loader? This is because BootstrapClassLoader is written in C++ and Java is null at load time

    If you want to getParent(), it’s null. If you want to getParent(), it’s null. If you want to getParent(), it’s null. So will the Java. Lang. NullPointerException null pointer exception

  • Object object = new Object();
    // BootStrap starts the class loader
    //System.out.println(object.getClass().getClassLoader().getParent().getParent());
    //System.out.println(object.getClass().getClassLoader().getParent());
    System.out.println(object.getClass().getClassLoader());
    
    System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
    
    // Custom class
    ClassLoaderDemo classLoaderDemo = new ClassLoaderDemo();
    System.out.println(classLoaderDemo.getClass().getClassLoader().getParent().getParent());
    System.out.println(classLoaderDemo.getClass().getClassLoader().getParent());
    Copy the code

System.out.println(classLoaderDemo.getClass().getClassLoader());

! [image-20201030104905503](https://img2020.cnblogs.com/blog/1875400/202011/1875400-20201120162746376-1786182009.png) * ```java Object object = new Object(); // BootStrap system.out.println (object.getClass().getClassLoader())); System. The out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "); // Custom class ClassLoaderDemo ClassLoaderDemo = new ClassLoaderDemo(); System.out.println(classLoaderDemo.getClass().getClassLoader().getParent().getParent()); System.out.println(classLoaderDemo.getClass().getClassLoader().getParent()); System.out.println(classLoaderDemo.getClass().getClassLoader());Copy the code
  • In the output, sun.misc.Launcher is the entry program for jVM-related calls

Parents delegate

  • 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 classloader (the root loader). 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 parental delegation is that, for example, any loader that loads the java.lang.Object class in the rt.jar package delegates the class to the top bootstrap class loader, ensuring that the class loaders used end up with the same Object

The sandbox security

  • Sandbox security mechanismIs a JVM’s self-protection mechanism based on parental delegation, assuming you want to write onejava.lang.StringClass, because of the principle of the parent delegate mechanism, the request is handed firstBootStrapClassLoaderTried to load, butBootStrapClassLoaderClasses are first looked up by package and class name when they are loadedrt.jarIf yes, the class is loaded firstrt.jarClasses in packages,This ensures that the Java mechanism will not be broken and that your malicious code will not contaminate the Java source code(For example, the custom String class)

The loading order of the class loader

  • 1: whenAppClassLoaderLoads aclassInstead of trying to load the class itself, it delegates the classloading request to the parent classloaderExtClassLoaderTo complete
  • 2: whenExtClassLoaderLoads aclassInstead of trying to load the class itself in the first place, it delegates the classloading request toBootStrapClassLoaderTo complete
  • 3: ifBootStrapClassLoaderLoading failed (for example in$JAVA_HOME/jre/libWas not found inclass), can useExtClassLoaderTo try to load
  • If 4:ExtClassLoaderAlso failed to load, will be usedAppClassLoaderTo load, ifAppClassLoaderIf the load fails, an exception is reportedClassNotFoundException

Native Method Stack

Native Interface Indicates the local Interface

  • Native Interface, which is used to integrate different programming languages for Java, is originally used to integrate C/C++ programs, Java was born when C/C++ was popular, to get a foothold, you have to call C/C++ programs. As a result, Java creates an area of memory for processing code marked as Native by registering native methods in the Stack and loading the Native Libraies during Execution by the Execution Engine

    This approach is being used less and less today, except in hardware-related applications, such as driving printers through Java programs or managing production equipment through Java systems, which are rare in enterprise applications. Because the communication between heterogeneous domains is very developed, for example, Socket communication can be used, Web Service can also be used, and so on, I will not introduce

Native Method Stack

  • The idea is to register these native methods in a Stack and load the native method library, the Native Libraies, at Execution Engine Execution

    Next, let’s take a look at the multithreading section below to understand what a Native method is. Start0 () : start0() : start0() : start0() : start0() Find that it is just a method that uses the native keyword modifier (private native void start0();) But there are only statements but no concrete implementation!

Program Counter Register

  • Program Counter Register, also known as PC Register

  • Simply put, the PC register is the register that stores the address of the next instruction to be executed. Its content always points to the address of the next instruction to be executed. The address here can be a local pointer, or it can be the offset corresponding to the start instruction of the method in the method area

  • Each thread has a program counter, thread is private, is a pointer that points to the method area of bytecode (used to store to the address of the next instruction, also the instructions to be executed code), the Execution Engine Execution Engine reads the next instruction, is a very small memory space, almost can ignore don’t remember

  • This small area of memory is a line number indicator of the bytecode being executed by the current thread, and the bytecode interpreter changes the value of this counter to select the next bytecode instruction to be executed

If a Native method is executed, the counter is empty

  • To complete branch, loop, jump, exception handling, thread recovery and other basic functions. No OutOfMemory (OutOfMemory=OOM) error occurs

Method Area

  • An area of Runtime memory shared by threads that stores structural information for each class, such as the Runtime Constant Pool, field and method data, and bytecode content for constructors and common methods. The above specification is implemented differently in different virtual machines. The most typical examples are PermGen space and Metaspace.
  • Instance variables are stored in heap memory, independent of the method area

The Stack (Stack)

Stack tube runs, heap tube stores

The stack

  • Also called memory stack, the competent Java program is running, is created when thread creation, its life cycle is to follow the thread of life cycle, the end of the thread stack memory also release * *, there is no garbage collection for stack problem * *, as long as the thread one end of the stack is over, life cycle and thread, thread is private. The eight basic types of variables, reference variables of objects, and instance methods are all allocated in the stack memory of the function

What does the stack store

  • The stack frame mainly stores three types of data:
    • Local Variables: Input and output parameters and Variables within methods
    • Operand Stack: Records the operation of loading and unloading the Stack
    • Frame Data: includes class files, methods, and so on

Stack operation principle

  • All the data in the Stack exist in the format of Stack Frame. Stack Frame is A memory block, A data set, and A data set related to methods and run-time data. When A Method A is called, A Stack Frame F1 is generated and pushed into the Stack.

    Method A calls method B, and the stack frame F2 is pushed,

    Method B in turn calls method C, resulting in the stack frame F3 being pushed

    .

    After execution, F3 stack frame, F2 stack frame, and F1 stack frame…… will pop up

    Follow the “fifo/LIFO” principle

  • A stack frame will be created when each method is executed, which is used to store information such as local variable table, operand stack, dynamic link, method exit and so on. The process of each method from invocation to completion of execution corresponds to the process of a stack frame being put into and out of the virtual machine

  • Depending on the implementation of the particular JVM, the stack size usually ranges from 256K to 756K, which is equal to about 1Mb

    • The graph shows two stack frames in a stack:
      • Stack frame 2 is the method that gets called first, pushed first
      • Method 2 then calls method 1, with frame 1 at the top of the stack
      • Stack frame 2 is at the bottom of the stack. After execution, stack frame 1 and stack frame 2 pop up successively
      • The thread terminates and the stack is released
    • Each execution of a method generates a stack frame, which is stored at the top of the stack (back in, back out). The top stack is the current method, and the stack frame is automatically removed from the stack when the method is finished

StackOverflowError

  • Legend: Recursively, the test() method is called inside the test() method

    A stack is a block of memory that has a size and length. Observation code that, as long as the code a run, the test () method has been conducted into the stack operation, and not out of the stack operation, the result would be beyond the size of the stack, causing the stack overflow error, namely the Java. Lang. StackOverflowError

  • java.lang.StackOverflowErrorAn error, not an exception! The proof is as follows:

Stack + heap + method area interaction

HotSpot

  • It is usually not explicitly specified that the JVM is HotSpot

    • One implemented by Sun complies with the JVM specification, Java HotSpot
    • One implemented by BA conforms to the JVM specification, Java Rocket
    • They were eventually acquired by Orcle and became a unified Java HotSpot
  • HotSpotObjects are accessed using Pointers: access is stored in the Java heapClass metadataReference stores the address of the object directly

    • For example:MyObject myObject = new MyObject();The left-hand side of the equals signMyObject myObjectthemyObjectIt’s a reference, inside the Java stack. On the right-hand sidenew MyObject().newOut of theMyObjectThe instance object is in the heap. Simply put, this is a reference in the Java stackmyObjectIt points to the heapMyObjectInstance objects

Heap (Heap)

Reactor architecture

  • Prior to Java7, there was only one heap memory per JVM instance, and the size of the heap memory was adjustable. After the class loader reads the class file, it needs to put the class, method, and constant variables into the heap memory to save the real information of all reference types for the implementation

    • The heap is logically divided into three parts: new + old + permanent
    • The heap memory is divided into three parts:
      • Young Generation Space
      • Tenure Generation Space, old age, old age
      • The Permanent Space
    • Java 7 before, the heap structure diagram is as follows, whileJava8Then onlyTransformed the permanent zone into a meta-space
  • To sum up, the in-heap existence is logically divided into newborn + endowment + meta-space, while the in-heap existence is physically divided into newborn + endowment

The lifetime of an object in the heap

For the first time on

  • The spawns are areas where classes are born, grow, and die, where a class is created, applied, and finally collected by the garbage collector to end its life. The freshman area is divided into two parts: Eden Space and Survivor Space. All classes are created in Eden area. There are two Survivor zones: Survivior 0 space and Survivor 1 space. When Eden runs out of space and the program needs to create objects again, the JVM’s garbage collector will perform a Minor GARBAGE collection (YGC) on Eden. Destroy objects in Eden that are no longer referenced by other objects. Then move the remaining objects in the Eden area to the surviving 0 area. If the surviving 0 area is also full, then recycle the garbage in the area and move to the 1 area. What if sector one is full? If the pension area is also Full, MajorGC (FullGC), also called strong GC, will be generated at this time to clean up the memory of the pension area. If the FullGC is performed in the pension area and the object still cannot be saved, OOM exception “OutOfMemoryError” will be generated.
  • If there is a Java. Lang. OutOfMemoryError: Java heap space is unusual, illustrate the Java virtual machine heap memory is not enough, there are two reasons:
    • 1: The heap memory setting of the Java VM is insufficient. You can use -xms and -xmx to change the heap memory setting
    • 2: A lot of large objects are created in the code and cannot be collected by the garbage collector for a long time (there are references)

Interview questions: written grammar

  • Main point:
    • Primitive types pass values, and reference types pass addresses to objects
    • The base type value does not change, but the reference type value changes

MinorGC process (YGC, light GC)

  • The Java heap can also be subdivided from a GC perspective into:New area(Eden Zone, From Survivor zone and To Survivor zone) and pension zone
    • Freshmen are divided into Eden, From Survivor 0, and To Survivor 1. The default ratio is 8:1:1, that is, From and To are always equal
    • The freshman area takes up one third of the heap space and the endowment area takes up two thirds of the heap space
  • From and to zones, their positions and names, are not fixed and will be swapped after each GC
  • After GC there is swap, who is empty who is to
Copy –> empty –> swap
  • Eden, From Survivor replication To Survivor, age +1
    • First of all, when Eden area is full, the first GC will be triggered, and the surviving objects will be copied to From Survivor area 0. When Eden area triggers GC again, the Eden area and From area will be scanned and garbage collected for these two areas. After the second collection, the surviving objects, Then copy directly To the To area (if there are objects whose age has reached the old standard, then assign To the pension area), and at the same time, add the age of these objects +1
  • Clear Eden and From Survivor
    • Clear objects in Eden and From Survivor, i.e., swap after replication, who is empty and who is to
  • To Survivor and FromSurvivor swap
    • Finally, To Survivor and From Survivor are swapped, and the original To Survivor becomes the From Survivor zone for the next GC, and some objects are copied over and over in the From and To zones. This is done 15 times (determined by the JVM parameter MaxTenuringThreshold, which defaults to 15), and is eventually saved to the pension if it still survives

HotSpot Memory Management

  • Different objects have different life cycles. 98% of them are temporary objects, that is, the life cycle of these objects only exists in Eden area

  • In practice, a Method Area, like a heap, is an Area of memory shared by threads and used to store loads from the virtual machine: While the JVM specification describes the method area as a logical part of the Heap, it also has a nickname, non-heap, to separate it from the Heap

  • For the HotSpot VIRTUAL machine, many developers are used to referring to the method area as a “Parmanent Gen”, but strictly speaking the two are essentially different, or the method area is implemented using a persistent generation, which is an implementation of the method area (rather like an interface).In jdk1.7, the string constant pool from the original permanent generation has been removed

Permanent section (before Java7)

  • The permanent storage area is a resident area of memory used to store metadata about classes and interfaces carried by the JDK itself. That is, it stores information about classes that are necessary for the runtime environment. Data loaded into this area is not collected by the garbage collector

Tuning heap parameters

  • Take JDK1.8+HotSpot as an example

Java7

Java8

  • JDK 1.8 removed the original permanent generation and replaced it with a meta-space. The nature of a metaspace is similar to that of a permanent generation
    • The biggest difference between a meta-space and a permanent generation is that the permanent generation uses the heap memory of the JVM, whereas meta-spaces after Java8 are not in the virtual machine but use native physical memory
    • Therefore, by default, the size of the meta-space is limited only by local memory. Class metadata intonative memoryThe string pool and the static variables of the class are put into the Java heap so that the metadata of the class can be loaded no longer byMaxPermSizeControlled by the actual available space of the system

By default, the JVM uses a quarter of the physical memory (*)

An introduction to heap memory tuning

  • parameter instructions
    -Xms Set the initial memory allocation size. The default size is 1/64 of the physical memory
    -Xmx Maximum memory allocated. The default value is 1/4 of the physical memory
    -XX:+PrintGCDetails Print verbose GC processing logs
    // Returns the maximum amount of memory that the Java virtual machine is trying to use
    long maxMemory = Runtime.getRuntime().maxMemory();
    // Returns the total amount of memory in the Java virtual machine
    long totalMemory = Runtime.getRuntime().totalMemory();
    System.out.println("-Xmx:MAX_MEMORY ="+maxMemory+"(bytes)"+(maxMemory/(double)1024/1024) +"MB");
    System.out.println("-Xms:TOTAL_MEMORY ="+totalMemory+"(bytes)"+(totalMemory/(double)1024/1024) +"MB");
    Copy the code

How to configure JVM memory parameters in IDEA

  • In [Run] -> [Edit Configuration…] -> [VM options], enter parameters-Xms1024m -Xmx1024m -XX:+PrintGCDetailsThen save the application and exit
  • Print the memory and heap structure details again, changed to the newly modified 1024MB
    • The heap (Java8) consists of the freshman area (Eden, survival 0 from, survival 1 to), pension area and meta-space

Heap overflow (OutOfMemoryError)

  • The Full GC cannot process the new object until the heap is exhausted, which causesOOMHeap overflow error

  • If there is a Java. Lang. OutOfMemoryError: Java heap space is unusual, illustrate the Java virtual machine heap memory is not enough, the heap memory. There are two reasons for this: 1) The Java VIRTUAL machine’s heap memory Settings are too small and can be adjusted with the arguments -xms and -xmx. 2) The code creates a large number of objects that cannot be collected by GC for a long time.

Java Garbage Collection (GC)

What is GC (Generational collection algorithm)

The number of frequent collection of Young area

Old areas are less frequently collected

Basically fixed element space

Interpret GC log information

YCG log interpretation

  • Log contents

    [GC (Allocation Failure) 
    [PSYoungGen: 250570K->32K(270848K)] 497085K->344850K(658432K), 0.0540353 secs] 
    [Times: user=0.24 sys=0.02, real=0.05 secs] 
    Copy the code

FULL Reads GC logs

  • Log contents

    [Full GC (Ergonomics) [PSYoungGen: 888K->0K(270848K)] [ParOldGen: 184327K->49907K(190976K)] 185215K->49907K(461824K), [Metaspace: 3286K->3286K(1056768K)], 0.0126262 secs] [Times: User sys = = 0.08 0.00, real = 0.01 secs]Copy the code

regular

  • Split with “[]”
  • Name: Memory usage before GC -> Memory usage after GC

Big GC4 algorithm

GC algorithm overview

  • The JVM does not always collect the above three memory regions together during GC, but most of the time, the collector refers to the new generation. Therefore, there are two types of GC(minor GC) and global GC(Major OR Full GC).
  • The difference between Minor and Full GC
    • Minor GC: Generation-only GC refers to garbage collection that occurs in the new generation. Since most Java objects have low survival rates, minor GC is very frequent and generally fast
    • Global GC (major or Full GC) : Refers to a garbage collection that occurred in the old days, usually accompanied by at least one Minor GC (but not always) that is usually 10 times slower than a Minor GC

The four algorithms

Reference counting method
  • The reference-counting algorithm sets a counter for each object that is +1 when there is a reference to the object, -1 when the reference is invalid, and 0 when the counter is zero, the JVM considers the object to be no longer in use and “junk.

    Reference counting is simple and efficient. It does not solve the problem of circular reference questions (object A refers to object B, and object B refers to object A, but A and B are not referenced by any other objects), and there is A lot of extra overhead with each increment and decrement of counters, so this algorithm has been discontinued after JDK1.1

Copying algorithms
  • The Minor GC used in the New generation, which uses a copy algorithm

  • The principle of

    • The Minor GC moves all the live objects in Eden to the Survivor region. If the Survivor region does not fit, the remaining live objects are moved to the Old Generation, so that once collected, Eden becomes empty
    • After Eden (including a Survivor region, suppose From region) is born, and after a Minor GC, if the object is still alive and can be accommodated by another Survivor region (already assumed From region, here to region), That is, the TO region has enough memory to store Eden and surviving objects in the From region), the replication algorithm is used to copy the surviving objects to another Survivor region (the TO region), and then clean up the Eden and Survivor region used (the From region). And set the age of these objects to 1. Each time the object passes a Minor GC in a Survivor zone, the age of the object is +1. When the age of the object reaches a certain value (15 by default, set with -xx :MaxTenuringThreshold), the object becomes old
    • -xx: MaxTenuringThreshold –> Sets the number of times an object can survive in the new generation
  • The dynamic demonstration

    • explain

      • GC in the younger generation is mainly Copying algorithms

      • HotSpot JVMThe young generation is divided into three parts: Eden zone, surviving 0 zone and surviving 1 zone. The default ratio is 8:1:1. In general, newly created objects are allocated to the Eden zone (with special treatment for large objects), and if they are still alive after the first Minor GC, they are moved to the Survivor zone.Each time an object survives a Minor GC in a Survivor zone, its age increases by one year, and when it reaches a certain age, it is moved to the old age. Because the objects in the young generation are basically in the day and night death (90%), so inThe garbage collection algorithm of the younger generation uses the replication algorithmThe basic idea of the copy algorithm is to divide the memory into two pieces and use only one piece at a time. When the memory is used up, the surviving objects are copied onto the other piece.The copy algorithm does not generate memory fragmentation

      • At the beginning of GC, objects will only exist in the Eden zone and in the Survivor zone named “From”, where the Survivor zone “To” is empty. Following the GC, all surviving objects in Eden are copied To “To”, and surviving objects in “From” are moved based on their age. Objects whose age reaches a certain value (age threshold, which can be set by -xx :MaxTenuringThreshold) are moved To the aged generation, and objects that do not reach the threshold are copied To the To region.After this GC, the Eden and From areas have been emptied. At this point, From and To switch roles, so the new “To” is the “From” before the last GC, and the new “From” is the “To” before the last GCEither way, the Survivor region named To is guaranteed To be empty. The Minor GC repeats this process until the To region is filled, after which all objects are moved To the aged generation

        Because the survival rate of objects in Eden area is low, 10% of the two pieces of memory are generally used as idle and active regions, while the other 80% of memory is used to allocate memory for new objects. Once GC occurs, move 10% of the From active range and the remaining 80% of Eden objects alive to 10% of the TO free range, then free the previous 90% of memory, and so on

  • The disadvantages of the replication algorithm are also quite obvious

    • 1: It wastes half of the memory, which is fatal
    • 2: If the object has a very high survival rate, which can be assumed to be 100%, then we need to copy all objects and reset all reference addresses. The time it takes to replicate this work becomes significant when the object’s survival rate reaches a certain level. Therefore, it is not difficult to see from the above description that in order to use the replication algorithm, the survival rate of the object must be very low, and most importantly, we must overcome the 50% memory waste.
Mark-sweep
  • The old age is usually implemented by tag cleanup or a mixture of tag cleanup and tag cleanup

  • The principle of

    • The algorithm is divided into two stages, marking and cleaning, marking the objects to be reclaimed first, and then collecting them uniformly. Like:

    • With popular words explain tag removal algorithm, that is, when the program is running, if you can use the memory is exhausted, the GC thread will be triggered and will pause, then will be recycled object tags again, finally unified recycling these objects, complete tag cleanup let the application resume next

  • disadvantage

    • 1: First, it is inefficient (recursive and full heap object traversal) and the need to stop the application while GC is being performed, which leads to a poor user experience
    • 2: Secondly, the main disadvantage is that the free memory cleared by this way is discontinuous. It is not difficult to understand that our dead objects are randomly appearing in all corners of the memory. After they are cleared, the layout of the memory will naturally be chaotic. To cope with this, the JVM has to maintain a free list of memory, which is another overhead. And when allocating array objects, it’s not easy to find contiguous memory
Mark-compact
  • Full name: Mark clearing compression algorithm, abbreviation: Mark collating algorithm

  • The principle of

    • In the detangling phase, marked objects are no longer recycled, but are moved by all living objects on one side, and then directly cleared of memory beyond the boundary. As you can see, marked living objects are sorted by memory address, while unmarked memory is cleaned up. This way, when we need to allocate memory for new objects, the JVM only needs to hold the starting address of memory, which is significantly less overhead than maintaining a free list

      The mark/tidy algorithm can not only make up for the mark/clear algorithm, the memory area scattered disadvantage, but also eliminate the copy algorithm, the high cost of half the memory

Mark-sweep-compact

A small summary

Generational collection algorithm (*)
  • Current commercial virtual machines are using generational collection algorithm, itThe memory is divided into chunks based on the object lifetime, typically dividing the Java heap into new generation and old generation, and then adopting the most appropriate garbage collection algorithm based on the characteristics of each generationIn the new generation, every garbage collection finds that a large number of objects have died and only a few have survived, so the selection is madeReplication algorithmIn the old age, because the object has a high survival rate, there is no extra space for it to allocate guarantees, it must be usedMark clearorMark compressionAlgorithm to do the recycling
Young Gen
  • The young generation is characterized by smaller memory space compared with the old generation and lower object survival rate

    The efficiency of the replication algorithm depends only on the size of the current living object, so it is suitable for young generation recycling. The problem of low memory utilization of the replication algorithm can be alleviated by designing two Survivor zones in the virtual machine.

Tenure Gen
  • The old age is characterized by large memory space and high object survival rate

  • In this case, there are a large number of objects with high survival rate, and the replication algorithm becomes obviously unsuitable. It is usually implemented by tag cleanup or a mixture of tag cleanup and tag cleanup

    • The cost of the marking phase (Mark) is proportional to the number of viable objects. At this point, for the old era, there are some differences between tag clearing or tag sorting, but can be used through multi-core/thread, on the form of concurrent, parallel markup efficiency
    • The overhead of the Sweep phase is positively correlated with the size of the managed memory space. But Sweep’s “execution-in-place” feature is that the recycling process has no object movement. Compared with other collection algorithms with object movement steps, it is still the most efficient. But memory fragmentation needs to be addressed
    • The overhead of the Compact phase is in proportion to the data of the living object. As described above, moving a large number of objects is expensive and not an appropriate first choice for older generations
  • Based on the above considerations, old age is generally implemented by tag cleanup or a mixture of tag cleanup and tag cleanup. Take the CMS collector in virtual machines as an example. The CMS is implemented based on Mark-sweep and has a high recycling efficiency for objects. For the fragmentation problem, CMS uses Serial Old collector based on Mark-Compact algorithm as a compensation measure: When memory collection is poor (due to a Concurrent Mode Failure due to fragmentation), Serial Old is used to perform Full GC to defragment Old memory.

Comparison of GC garbage collection algorithms
  • Memory efficiency: copy algorithm > mark clearing algorithm > Mark algorithm (the efficiency here is just a simple comparison of time complexity, the actual situation is not necessarily)
  • Memory uniformity: copy algorithm = tag collation algorithm > tag cleaning algorithm
  • Memory utilization: mark collation algorithm = mark clearing algorithm > copy algorithm
  • It can be seen that in terms of efficiency, replication algorithm is well-deserved, but wasted too much memory, and in order to try to balance more than the above mentioned three indicators, tag/sorting algorithm is relatively more smooth, but the efficiency is still not satisfactory, it is more than the replication algorithm a tag, and more than tag/remove the memory of a finishing process

The interview questions

The JVM memory model and partitions need to be detailed to what is placed in each partition
Partitions in the heap: Eden,Survivor from to, and their respective characteristics
What are the principles and characteristics of GC’s three collection methods: tag clearing, tag collation and copy algorithm
When does the Minor and Full GC occur
Code loading sequence exercise
  • public class CodeBlock { / / the main class
        {
            System.out.println("Building block 444 for CodeBlock.");
        }
        static {
            System.out.println("Static CodeBlock 555 for CodeBlock");
        }
        public CodeBlock(a){
            System.out.println("Constructor of CodeBlock 666");
        }
    
        public static void main(String[] args) {
            System.out.println("Secant line =============CodeBlock's main method 777");
            new CodeWb();
            System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
            new CodeWb();
            System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
            newCodeBlock(); }}class CodeWb{
        public CodeWb(a){
            System.out.println("Code constructor 1111");
        }
        {
            System.out.println("Code building block 2222");
        }
        static {
            System.out.println("Static Code block 3333 of Code"); }}Copy the code

    Running results:Static first is executed only once. Loading order: Static Block > Constructor Block > Constructor method

JMM (Java Memory Model)

The volatile keyword

  • Volatile is a lightweight synchronization mechanism provided by the Java Virtual machine
    • Guaranteed visibility
    • Atomicity is not guaranteed
    • Disallow command reordering

JMM

  • The Java Memory Model (JMM) itself is an abstract concept that doesn’t really exist. It describes a set of rules or specifications that define how variables in a program (including instance fields, static fields, and elements that make up array objects) can be accessed
  • Since the JVM runs programs in threads, and each thread is created with a working memory (sometimes called stack space) created by the JVM,Working memory is the private data area for each threadThe Java memory model specifies that all variables are stored inMain memoryMain memory is a shared memory area accessible to all threads.However, the thread’s operations on variables (reading and assigning values, etc.) must be carried out in the working memory, first copying variables from main memory to the thread’s own working memory space, then performing operations on variables, and then writing variables back to main memoryVariables in main memory cannot be manipulated directly. Working memory in each thread stores variables in main memoryVariable copyTherefore, different threads cannot access each other’s working memory, and the communication between threads must be completed through the main memory. The brief access process is shown as follows:

visibility

  • A notification mechanism

  • public class JmmDemo {
        //JMM visibility (notification)
        public static void main(String[] args) {
            Mynumber mynumber = new Mynumber();
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"* * * * * * * * * * * * * * * * * * * * * * * *");
                try {
                    Thread.sleep(3000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                mynumber.addTo1205();
                System.out.println(Thread.currentThread().getName()+"\t update number,number value: "+mynumber.number);
            },"AAA").start();
    
            while (mynumber.number == 10) {
                // There needs to be a notification mechanism to tell the main thread that number has been changed to 1205, jumping out of while
            }
            System.out.println(Thread.currentThread().getName()+"\t mission is over"); }}class Mynumber {
        int number = 10;
    
        public void addTo1205(a) {
            this.number = 1205; }}Copy the code

    The result: changes the value of the number variable, but the program does not break out of the while loop and terminates. Thread A changes the value of the variable, but no one notifies the main thread

  • Add the keyword volatile to modify number

    class Mynumber {
        volatile int number = 10;
    
        public void addTo1205(a) {
            this.number = 1205; }}Copy the code

    Running results:

atomic

  • Atomicity refers to the fact that an operation is uninterruptible, even in a multi-threaded environment, and once an operation is started it will not be affected by other threads. Such as for A static variable int x, two threads of his assignment at the same time, the thread A assignment to 1, and thread B assignment 2, no matter how threads run, finally the value of x is either 1, or 2, thread and thread B, the operation is no interference between this is atomic operation, the characteristics of the cannot be interrupted. A little note that for 32 bit system, long data and type double data (for basic data types, byte, short, int, float, Boolean, char, speaking, reading and writing is atomic operation), their reading and writing is not atomic, That is, if there are two threads reading and writing data of type long or double at the same time, it will interfere with each other. For 32-bit virtual machines, each atomic read and write is 32 bits, while long and double are 64 bits of storage. After the first 32 bits of atomic operation, thread B’s turn to read happens to read only the last 32 bits of data, so it may read a variable that is neither original nor modified by the thread. It may be the value of a “half variable”, that is, the 64-bit data is divided into two reads by two threads. But don’t worry too much, because reading “half a variable” is rare, at least in today’s commercial virtual machines, almost all 64-bit data reads and writes are performed as atomic operations, so don’t worry too much about this problem

order

  • Order is for a single thread of execution code, we always think that is in order to perform code execution, there is nothing wrong with this understanding and, after all, for a single thread that’s true, but for a multithreaded environment, out-of-order phenomena may occur, because the program compiled into machine code instructions may occur after rearrangement, After rearrangement of instructions with the original order is not consistent, want to know is that in a Java program, if in this thread, all operations as an orderly behavior, if it is a multithreaded environment, observed in one thread to another thread, all operations are disorderly, within the first half of the sentence refers to a single thread to ensure serial semantic consistency, The second half of the sentence refers to the instruction rearrangement phenomenon and working memory and main memory synchronization delay phenomenon