JVM memory model

Thread-isolated data area:

  • Program counter

    Small memory space, line number indicator of bytecode executed by the current thread.

    Since Java is a multithreaded language, threads compete for CPU resources based on time slice polling. If a thread runs out of time or is robbed of CPU resources prematurely for other reasons, the exiting thread needs a separate program counter to record a running instruction.

    The memory area is the only area that is not OOM

  • Virtual Machine Stack (Bullet clip)

    Stack: First in last out

    The virtual machine stack stores data, instructions, and return addresses required by the current thread’s execution method while the JVM is running.

    Each piece of data in the stack is a stack frame. Each time a Java method is called, a stack frame is created and merged into the stack. Once the corresponding call has been made, the stack is removed. The Java virtual machine stack is thread-based, and when all stack frames are off the stack, the thread ends.

    Each stack frame contains four areas: local variable table, operand stack, dynamic link, and return address.

  • Local method stack

    The function of the Native method stack is similar to that of the Java virtual machine stack, which is used to manage calls to Java functions, and the Native method stack, which is used to manage calls to Native methods.

An area shared by threads

  • Methods area

    The method area is used to store data such as class information that has been loaded by the virtual machine, constants, static variables, and code compiled during just-in-time compilation. The runtime constant pool is part of the method area.

  • The Java heap

    The heap is the largest area of memory on the JVM, where almost all of the objects we request are stored. When we say garbage collection, the object of operation is the heap.

    Method to store static data, the Java heap stores data that is often dynamically created and recycled, which improves garbage collection efficiency.

2 Garbage Collection

2.1 Band collection theory

Vm garbage collection follows the generation collection theory.

  1. Most objects are ephemeral, which means you create an object, use it, and then recycle it.
  2. Objects that have survived multiple garbage collections are harder to recycle.

According to the above two theories, the dying objects are put in one area, and the objects that are difficult to recover are put in another area, which constitutes the Cenozoic era (1/3) and the old era (2/3).

2.2 the GC type

  1. Minor GC/Young GC: Refers to the collection of only the new generation.
  2. Major GC (Old GC) : Refers to collecting only Old GC.
  3. Heap Collection (Full GC) : Collects the entire Java heap and method area (note the inclusion of the method area).

2.3 Garbage collection algorithm

There are two algorithms for garbage object detection: reference counting method and reachability analysis method.

  • Accessibility analysis:

    The basic idea of this algorithm is to search down from a series of objects named “GC Roots” as the starting point, and the search path is called the Reference Chain. When an object is not connected to GC Roots by any Reference Chain, it is proved that the object is unavailable.

  • Reference counting method

    Reference counting mage garbage collection strategy of early in this method, the heap every object has a reference count, whenever there is a place to quote him, reference count + 1, when the reference fails, reference count is 1, any time the object reference count is zero is can be recycled, when an object is garbage collected, The object referenced by it has a reference count of -1, so garbage collection of one object in this method results in subsequent garbage collection of other objects.

  1. Replication algorithm

    Divide the available memory into two equally sized pieces by capacity and use 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.

    Replication algorithm is simple to implement, efficient to run, memory replication, no memory fragmentation. But its memory utilization is only half.

    The copy-recovery algorithm is suitable for the new generation, because most objects die overnight, so there are fewer objects copied in the past, and the efficiency is naturally high. The one-time cleaning of the other half is fast.

  2. Mark-clear algorithm

    The algorithm is divided into “mark” and “clear” two stages: first, mark all the objects that need to be recycled, after the completion of marking all the marked objects.

    The recovery efficiency is not stable. If most objects are dead overnight, the recovery efficiency is reduced, because a large number of marked objects and recovered objects are needed, and the recovery efficiency is very low compared to copy.

    A large number of discrete memory fragments are generated after the flag is cleared.

    The more objects need to be recovered, the more work needs to be done to mark and clear, so the mark clearing algorithm is suitable for the old age.

  3. Mark-collation algorithm

    The first step is to mark all objects that need to be reclaimed. After the mark is done, the next step is not to clean up the reclaimed objects directly, but to move all surviving objects towards one end and then clean up the memory directly beyond the end boundary. Although there is no memory fragmentation, the efficiency of tag defragmentation algorithm is low.

    The difference between tag cleaning and tag clearing algorithms mainly lies in object movement. Not only does object movement burden the system, it also requires suspending the user thread throughout, and all references to the object need to be updated.

  4. Generational collection

    The new generation of replication algorithm, the old age of the label sorting algorithm.

3 How is a String created

In Java, there are usually two ways to create string objects:

  1. One is created as a String constant, such as String STR = “ABC”;

    The object is first checked to see if it is in the string constant pool, and if so, the object reference is returned, otherwise a new string will be created in the constant pool. This saves memory by reducing repeated creation of string objects with the same value.

  2. The other is that String variables are created with a new form, such as String STR = new String(” ABC “).

    First, when the class file is compiled, the “ABC” constant string will be put into the constant structure. When the class is loaded, the “ABC” will be created in the constant pool. Second, when calling new, the JVM command will invoke the String constructor and create a String in heap memory by referring to the “ABC” String in the constant pool. Finally, STR will refer to String.

    String STR = new String(” ABC “).intern(); If you call the intern method, it checks to see if there are any references to strings equal to the object in the string constant pool. If there are no references to strings encountered for the first time, it adds them to the constant pool. If so, it returns a string reference from the constant pool.

4. Meet often

  1. JVM memory structure say!

  2. When does a memory stack overflow occur?

    Java. Lang. StackOverflowError if appeared may be infinite recursion.

    OutOfMemoryError: The machine does not have enough memory because threads are being created and the JVM is requesting stack memory.

  3. Describe the process of new an object!

  1. Will Java objects be allocated on the stack?

    Yes, if the object does not satisfy escape analysis, then the virtual machine will be allocated on the stack in certain cases.

  2. What algorithms are available to determine whether an object is reclaimed, and what is used most by the actual virtual machine?

    Reference counting and root reachability analysis are the two most commonly used methods.

  3. What are the GC collection algorithms? What are their characteristics?

    Copy, mark clearing, mark finishing. Copy fast, but to waste space, no memory fragmentation. Tag clearance space utilization is high, but there is memory fragmentation. The markup algorithm has no memory fragmentation but has low performance when moving objects. The three algorithms have their own advantages and disadvantages.

  4. What does a complete GC flow look like in the JVM? How do objects advance to the old age? Objects are allocated in the Cenozoic region first. If there is not enough space, Minor GC.

Large objects (requiring a large amount of continuous memory space) directly enter the old state; Long-lived objects enter the senile state. If the object is still alive after the new generation is born and passes the first MGC, the age is +1, and if the age exceeds a certain limit (15), it is promoted to the senility state.

  1. What are the differences between reference relationships in Java?
  • Strong reference

    Object obj = new Object() is a strong reference. In any case, the garbage collector will never reclaim the referenced object as long as there is a strong reference association (reachable to the root).

  • Soft reference SoftReference

    Objects associated with soft references that are useful but not necessary are recycled just before the system runs out of memory (or is thrown out if there is still not enough space after the recycle).

  • A weak reference WeakReference

    Objects associated with weak references that are useful (to a lesser degree than soft references) but not necessary will only survive until the next garbage collection, when GC occurs and will be collected regardless of memory availability.

  • Phantom reference PhantomReference

    Ghost references receive a notification when the weakest garbage is collected, just to monitor whether the garbage collector is working properly.

  1. What is the difference between final, Finally and Finalize?
  • Final modifies classes, methods, and variables (member or local).

    • When modifying a class: indicates that the class cannot be inherited to prevent tampering (all member methods are implicitly defined as final methods).
    • Modifier: Locks a method to prevent it from being changed by an inherited class.
    • Modifier variable: indicates that it is a constant and can be assigned only once, after which its value does not change.
  • finally

    As part of exception handling, it can only be used in try/catch statements, with a block indicating that the statement must eventually be executed (with or without an exception thrown), and is often used when resources need to be freed.

  • finalize

    Finalize method in Object. If an Object overwrites the Finalize method, it will execute the Finalize method and recycle resources after being collected by GC. This method has a lot of uncertainty (no guarantee that the tasks in the method will be completed) and is expensive to run. Corresponds to the destructor in C++.

  1. String s = new String(” XXX “); How many objects are created?

    2,

    1. At the beginning the string “XXX” creates a string object in the constant pool when the class is loaded.
    2. When we call new, we create a String in the heap, and the char array in the String will reference the String from the constant pool.