preface

Recently read a deep understanding of Java virtual machine third edition, sorted out some basic structure diagram, is relatively complete, make notes, we study together.

Github.com/whx123/Java…

1. Data area diagram of the Running Java VM

Program counter

  • A program counter, which can be thought of as a line number indicator of the bytecode executed by the current thread
  • It is thread private.

Java virtual machine stack

  • The thread is private and has the same life cycle as the thread.
  • Each method execution creates a “stack frame” that stores information about local variables (including parameters), operand stacks, dynamic links, method exits, and so on.
  • Local variable tables store basic data types Boolean, byte, CHAR, short, and so on

Local method stack

  • It is similar to the virtual machine stack except that the virtual machine stack serves Java methods executed by the virtual machine, while the Native method stack serves Native methods.

The Java heap

  • The Java heap is the largest area of memory managed by the Java Virtual Machine and is shared by individual threads, created at JVM startup.
  • The size is set by the -xms and -xmx parameters, where -xms is the minimum memory that the JVM can request at startup and -xmx is the maximum memory that the JVM can request.

Methods area

  • It is used to store information about classes loaded by the virtual machine, constants, static variables, and an area of memory shared by individual threads. – You can use -xx :PermSize and -xx :MaxPermSize to limit the size of the method area.

2. Default allocation diagram for the heap

  • Java heap = old + New generation
  • Cenozoic = Eden + S0 + S1
  • The default ratio between the Cenozoic era and the old era is 1:2. You can set this parameter by using XX:NewRatio.
  • The default Eden: from: to = 8:1:1 can be set using the -xx :SurvivorRatio parameter

3. Method area structure diagram

A method area is an area of memory shared by each thread that stores data such as type information that has been loaded by the virtual machine, constants, static variables, and code caches compiled by the just-in-time compiler.

4. Memory layout diagram of objects

A Java object in the heap contains three parts: the object header, the instance data, and the completion fill:

  • The object header includes a Mark Word (storing hash codes, GC generation ages, etc.), a type pointer (a pointer to the object’s type metadata), and, in the case of an array object, a space to hold the length of the array
  • Instance data is the valid information stored by the object, including all the member variables of the object, and its size is jointly determined by the size of each member variable.
  • Alignment padding does not necessarily exist, but serves only as a placeholder.

5. Mark Word diagram for the object header

  • Mark Word is used to store the runtime data of the object itself, such as HashCode, GC generation age, lock status flags, locks held by threads, bias thread IDS, bias time stamps, etc.
  • In a 32-bit HotSpot virtual machine, if the object is not locked, the Mark Word 32bit space contains 25 bits to store the object hash code, 4 bits to store the age of the object, 2 bits to store the lock flag, and 1bit to be fixed at 0 for non-biased locking.

6. Associated structure diagram between the object and Monitor

How are objects associated with Monitor?

A Java object contains an object header in the heap memory. The header has the Mark Word, which stores the lock state, and the lock pointer points to the Monitor address. This is the underclass of Synchronized

7.Java Monitor working mechanism diagram:

A Java thread synchronization lock is called Monitor~.

  • Threads that want to get monitor first enter the _EntryList queue.
  • When a thread gets the object’s monitor, it enters the _Owner field, sets it to the current thread, and increments the _count counter by 1.
  • If a thread calls wait(), it enters the _WaitSet queue. It releases the monitor lock, assigning _OWNER to NULL, decreasing _count by 1, and entering the _WaitSet queue to block and wait.
  • If another thread calls notify()/notifyAll(), it wakes up a thread in _WaitSet, which tries again to acquire the monitor lock and enters the _Owner area if it succeeds.
  • When the synchronization method completes, the thread exits the critical section, sets the owner of Monitor to NULL, and releases the monitor lock. .

8. Create an object memory allocation flowchart

  • Objects are generally generated in Eden.
  • If the Eden area fills, the Young GC is triggered.
  • When the Young GC is triggered, the Eden area is cleared, and unreferenced objects are cleared directly.
  • If the object is still alive, it will be sent to the Survivor zone, Survivor =S0+S1.
  • At each Young GC, the surviving objects are copied to the unused Survivor zone, the other Survivor zone currently in use is cleared completely, and the use status of the two Survivor zones is swapped.
  • If the Young GC is moving an object larger than the upper limit of Survivor zones, the object goes straight to the old age.
  • An object cannot remain in the Cenozoic era forever. If it passes through multiple GC sessions and is still alive, exceeding the threshold of -xx :MaxTenuringThreshold, it goes directly to the old age. In short, the object has experienced many times rolling in the Yangtze River, the world of mortals, and finally becomes an elder (into the old age)

9. The reachability analysis algorithm determines the survival of the object

Reachability analysis algorithm is used to determine whether an object is alive

The core idea of the algorithm:

  • Through a series of objects called “GC Roots” as the starting point, search down from these nodes according to the reference relationship. The search path is called “reference chain”. When there is no reference chain between an object and GC Roots (from GC Roots to this object is unreachable), Proves that this object is not likely to be used again.

10. Schematic diagram of mark-clear algorithm

  • The mark-sweep algorithm is the most basic garbage collection algorithm.
  • The algorithm is divided into two stages, marking and clearing.
  • First, mark the objects that need to be recycled. After the mark is completed, all the marked objects are recycled.
  • You can, of course, reverse this by marking the surviving objects first and uniformly recycling the unmarked objects.
  • Two disadvantages of mark-clear are unstable execution efficiency and fragmentation of memory space

11. Schematic diagram of mark-copy algorithm

  • In 1969 Fenichel proposed “half partition replication”, dividing the memory capacity into two equal pieces, using only one piece at a time. When this block of memory is used up, the surviving objects are copied to another block, and the used memory space is cleaned up at a time
  • In 1989, Andrew Appel proposed “Appel recycling”, dividing the new generation into larger Eden and two smaller Survivor Spaces. Each memory allocation uses only Eden and one of the Survivor Spaces. When garbage collection occurs, the surviving objects in Eden and Survivor are copied to another Survivor space at once. The ratio of Eden to Survivor is 8:1
  • The disadvantage of “half copy” is that it wastes available space, and if the object has a high survival rate, it will be copied more times and become less efficient.

12. Schematic diagram of mark-collation algorithm

  • In 1974, Edward proposed the “mark-tidy” algorithm. The marking process is the same as the “mark-clean” algorithm, and then all surviving objects are moved to one end of the memory space, and then directly clean up the memory beyond the boundary ~
  • The essential difference between the mark-clearing algorithm and the tag sorting algorithm is that the former is a non-mobile recovery algorithm, while the latter is a mobile recovery algorithm.
  • There are advantages and disadvantages in moving living objects. Although moving memory is complicated, it is more cost-effective in terms of program throughput. Memory allocation is more complex when not moving, but garbage collection pauses are shorter, so it’s up to the collector to decide
  • The Parallel Scavenge collector is based on the mark-collation algorithm because of the focus on the swallow. The CMS collector is based on the mark-sweep algorithm because it focuses on latency.

13. Garbage collector composition diagram

  • Cenozoic collectors: Serial, ParNew, Parallel Insane
  • Collector: CMS, Serial Old, Parallel Old
  • Hybrid collector: G1

14. Life cycle diagram of a class

From the moment a class is loaded into virtual machine memory to the moment it is unloaded, the life cycle of a class goes through seven stages: load, validate, prepare, parse, initialize, use, and unload.

Loading stage:

  • Gets the binary byte stream that defines a class by its fully qualified name.
  • Transform the static storage structure represented by this byte stream into the runtime data structure of the method area.
  • Generate a java.lang.Class object in memory that represents the Class and acts as an access point for the Class’s various data in the method area

Validation:

  • The purpose of validation is to ensure that the information contained in the byte stream of the Class file meets the constraints required to ensure that the code does not compromise the virtual machine itself when it is run
  • Verification stage includes: file format verification, metadata verification, bytecode verification, symbol reference verification.

To prepare

  • The preparation phase is the phase where you formally allocate memory and set initial values for variables defined in a class (static variables).

parsing

  • The parsing phase is the process by which the virtual machine replaces symbolic references in the constant pool with direct references.

Initialize the

  • During the initialization phase, you actually start executing the Java bytecode defined in the class.

15. Class loader parent delegate model diagram

Parental delegation model composition

Startup class loaders, extension class loaders, application class loaders, custom class loaders

The parent delegate model work process is

If a classloader receives a class-loading request, it first does not attempt to load the class itself, but delegates the request to the parent classloader. This is true for every classloader, and only if the parent cannot find the specified class in its search scope (that is, ClassNotFoundException) will the child loader attempt to load it itself.

Why do we need the parental delegation model?

If there is no parent delegate, can the user define a java.lang.Object class with the same name as java.lang.String class and put it in the ClassPath? The comparison between classes and the uniqueness of the class are not guaranteed. The parental delegation model prevents multiple copies of the same bytecode from appearing in memory.

16. Conceptual structure diagram of stack frame

Stack frames are the data structures used to support virtual machine method calls and method execution. Stack frames store local variables, operand stacks, dynamic links, and method return address information for methods.

Local variable scale

  • Is the storage space for a set of variable values for method parameters and local variables defined within a method.
  • The capacity of the local Variable table is the smallest unit in Variable Slot.

The operand stack

  • Operand stack, also known as operation stack, is a last-in, first-out stack.
  • When a method is first executed, the operand stack of the method is also empty. During the execution of the method, various bytecode instructions write and extract contents into the operand stack, namely, push and unload operations.

Dynamic connection

  • Each stack frame contains a reference to a method in the runtime constant pool to which that stack frame belongs, and the reference is held to support Dynamic Linking during method invocation.

Method return address

  • When a method starts executing, there are only two ways to exit the method. One is when the execution engine encounters bytecode instructions returned by any of the methods. Another way to exit is when an exception is encountered during method execution.

17.Java Memory model diagram

  • The Java memory model specifies that all variables are stored in main memory
  • Each thread also has its own working memory
  • The working memory of a thread holds a main memory copy of variables used in the thread
  • All operations by a thread on a variable must be done in working memory rather than directly reading or writing to main memory.
  • Different threads cannot directly access variables in each other’s working memory, and the transfer of variables between threads requires data synchronization between their own working memory and main memory.

18. Thread state transition diagram

  • New: A thread that has not been started since it was created is in this state
  • Running: The thread is startedStart ()Method will enter the state.
  • Waiting: a thread in this state is not allocated processor execution time, generallyPark () LockSupport: :Timeoout is not setObject::wait()Method, forcing the thread into an infinite wait state.
  • Timed Waiting: Threads in this state are not assigned processor execution time and are automatically woken up by the system after a certain amount of time.Sleep ()The method enters the state ~
  • Blocked: A thread enters this state while the program is waiting to enter a synchronization area
  • Terminated: The thread state of a Terminated thread. Terminated execution is Terminated

19. Class file format diagram

  • U1, U2, U4, and U8 represent unsigned numbers of 1 byte, 2 byte, 4 byte, and 8 byte respectively
  • A table is a compound data type consisting of multiple unsigned numbers or other tables as data items
  • The first four bytes of each Class file are called magic numbers.
  • Minor and Major Version indicate the minor or major version number
  • Following the primary and secondary version numbers is the entry to the constant pool, which can be likened to the repository of resources in the Class file ~

20.JVM parameters mind map

JVM tuning is a necessary bridge to advanced development, so accumulate JVM parameter configurations

Personal public account

  • If you are a good boy who loves learning, you can follow my public account and study and discuss with me.
  • If you feel that this article is not correct, you can comment, you can also follow my public account, private chat me, we learn and progress together.
    • Github address: github.com/whx123/Java…