Instructions before Reading

  1. Because I did not intend to share it here, I directly quoted some websites of some different concepts when TAKING notes. If it constitutes infringement or is suspected of infringement, either the author or the reader, please contact me and I will delete this part immediately and apologize.
  2. The notes here are only for my personal reading record, here is only for the purpose of sharing, do not spray.
  3. Here are basically the original words in the book condensed version, have not read this book white may not understand what I write, read this book if you forget a concept can try to find in here.
  4. If you have any better tips for my note-taking, please share them in the comments section.
  5. This is only part of the book, but not all of it.

Automatic memory management mechanism

There is a “high wall” between Java and C++ surrounded by dynamic memory allocation and garbage collection techniques. People on the outside want to get in, and people on the inside want to get out.

Java memory area and memory overflow exception

Runtime data area

Program counter

  1. Used to record the current execution of bytecode instructions (in layman’s terms, which line of code was executed).
  2. A thread has a separate program counter.

JAVA virtual machine stack

  1. The JAVA virtual machine stack is thread private (that is, one thread has a separate JAVA virtual machine stack).
  2. The JAVA virtual machine stack has the same life cycle as a thread.
  3. The JAVA virtual machine stack is used to store information about local variable methods, operand stacks, dynamic linking, method exits, and more.
    1. Local variables: Basic data types
    2. Object reference
    3. ReturnAdress type: an instruction pointing to a bytecode.
  4. Two anomalies
    1. The JAVA virtual machine stack cannot be dynamically extended. If the stack depth is greater than the allowed depth, a StackOverflowError is raised.
    2. The JAVA virtual machine stack can expand dynamically. If the stack cannot allocate enough memory (subject to physical conditions), an OutOfMemoryError is raised.

Local method stack

  1. Similar to the virtual machine stack
  2. The Native method stack serves Native methods used by the virtual machine (the virtual machine stack serves Java methods).
  3. StackOverflowError and OutOfMemoryError are thrown as well as the virtual stack.

The JAVA heap

  1. All threads share an area of the JAVA heap.
  2. The sole purpose of the JAVA heap is to hold objects, and all object instances, as well as arrays, are allocated in the JAVA heap.
  3. The JAVA heap is the primary area of garbage collection, also known as the “GC heap.”
  4. The JAVA heap can be subdivided into regions for better memory reclamation or faster memory allocation.
  5. The JAVA heap can be in a physically discrete memory space, as long as it is logically contiguous.
  6. OutOfMemoryError is thrown if there is no memory in the JAVA heap to complete the instance allocation.

Method Area

  1. A method area is an area of memory shared by threads that stores data such as class information, constants, static variables, code compiled by the just-in-time compiler, and so on.
  2. The Java Virtual Machine specification has very loose limits on the method area, and you can choose whether memory size is expandable and whether garbage collection is implemented.
  3. Generally speaking, garbage collection in this region is difficult to achieve satisfactory results, and the conditions of type unloading are quite harsh, but it is necessary to implement garbage collection in this region.
  4. If the method area cannot meet memory allocation requirements, OutOfMemoryError is thrown.

Runtime Constant Pool

  1. The runtime constant pool is part of the method area.
  2. One of the information contained in the Class file is the constant pool, which is used to store the various generated literal and symbolic references in the runtime constant pool when the Class is loaded into the method area.
  3. Typically, in addition to symbolic references to Class file descriptions, translated direct references are also stored in the runtime constant pool.
  4. An introduction to symbolic and direct references
  5. OutOfMemoryError is thrown if no more memory is available in the method area.

Direct Memory

  1. Direct memory is not part of the data area of the virtual machine at runtime, nor is it defined in the Java Virtual Machine specification, but it is also used frequently.
  2. Some methods can call out of heap memory, which can significantly improve performance (NIO classes).
  3. While not limited by the Java heap, it is still limited by native physical conditions, and it is possible to throw OutOfMemoryError.

HotSpot VIRTUAL machine object Exploration

Object creation

  1. When a new instruction is encountered, the first step is to check whether the parameter of this instruction can locate the symbolic reference of a class in the constant pool, and check whether the class referenced by the symbol has been loaded, parsed and initialized. If not, the class loading process needs to be performed first.
  2. After class loading checks are passed, memory needs to be allocated for the new objects.
    • There are two methods of distribution:
      • “Pointer collision” allocation: If the Java heap is perfectly neat (used memory on one side, unused memory on the other, with a pointer in the middle as a cutaway indicator), then allocating memory simply moves that pointer to the free portion of the heap by an amount equal to the size of the object.
      • “Free list” allocation: If the Java heap memory is not tidy, the VM needs to maintain a table to record which memory blocks are available, allocate a large chunk of memory from the list for instance allocation, and update the records on the table.
    • Concurrency problem: Threads are not safe in concurrency
      • Synchronize the operation of allocating memory space ———— In fact, the CAS is configured on the VM to ensure atomicity of the update operation.
      • Memory allocation is performed in a region of memory called a local thread allocation buffer (TLAB). If the TLAB memory of a thread is allocated, the TLAB will be re-allocated, and the reallocation requires synchronization lock. (Personal understanding: this method can reduce the number of synchronization locking.)
  3. After allocating memory, the virtual machine initializes the allocated memory space to zero (except for the object header), ensuring that the object instance can be used in Java code without assigning an initial value.
  4. The virtual machine sets the necessary information about the object, such as its class, hash code, and GC generation age, into the object header. Set the object header based on the current running status of the VM.
  5. A new object has been created for the VIRTUAL machine. For Java programs, you also need to execute methods to initialize objects as the programmer intended.

Object memory layout

  • In the HotSpot VIRTUAL machine, objects are stored in memory in three areas: object headers, sample data, and alignment units.
    • Object Head: divided into two parts:
      • Part 1: Runtime data used to store the object itself: hash code, GC generation age, lock status flags, thread held locks, bias thread ID, bias timestamp, etc., officially called “Mark Word”.
      • Part two: Type Pointers. The virtual machine uses this pointer to determine which class the object is an instance of. If the object is an array, the object must also have a block of data in its header that records the length of the array.
    • Instance Data: Stores the contents of various fields defined in program code (both parent and subclass definitions are recorded). . This part of the stored data is affected by the order in which the allocation policy parameters and fields are defined in Java source code.
    • Alignment fill: Serves only as a placeholder. The HotSpot Automatic memory management system requires that the object start address be an integer multiple of 8 bytes.

Object access location

  • Java programs operate on concrete objects on the heap using reference data on the stack. At present, there are two mainstream access methods:
    • Handle access: The Java heap allocates a block of memory for this purposeHandle to the pool, reference stores the handle address of the object, and the handle contains the specific address information of the instance data and type data of the object.
      • Advantages: When objects are moved (garbage collection moving objects are very common), the value of reference does not need to be changed very often, only the pointer to the handle instance data needs to be updated.
    • Direct pointer access: Reference stores object addresses.
      • Pros: Faster.

Garbage collector and memory allocation strategy

An overview of the

  • The stack doesn’t have to worry too much about garbage collection.
  • Memory allocation and collection in the Java heap and method areas are dynamic, and the garbage collector focuses on this portion of memory.

Is the subject dead

Reference counting method

  • Add a reference counter to the object. Each time a reference is made to the object, the count is incremented by 1. If the counter is 0, the object cannot be referenced again.
  • Advantage: judge efficiency is high
  • Disadvantages: It is difficult to solve the problem of objects referring to each other circularly.
  • Current mainstream Java virtual machines do not use reference counting to manage memory.

Accessibility analysis algorithm

  • Reachability Analysis: From a series of”GC RootsThe “object sets off for a downward search, taking a path calledReference ChainIf an existing object has no reference chain with any “GC Roots” object, the object is not referable.
    • GC Roots objects include: objects referenced in the virtual machine stack, objects referenced by static attributes in the method area, objects referenced by constants in the method area, and objects referenced by JNI in the local method stack.

Talk about reference

  • Citations are graded into 4 levels (attenuated from top to bottom) :
    • Strong references: The garbage collector never collects strongly referenced objects.
    • Soft reference: Before the memory is about to run out, the soft reference object is reclaimed for a second time. If the memory is still insufficient, an exception is thrown.
    • Weak references: This object can only survive until the next garbage collection occurs.
    • Virtual reference: equivalent to not being referenced. The only purpose of setting a virtual reference is to receive a spoof notification when the object is reclaimed by the collector.

To be or not to be

  1. Two flags need to be met before being recycled:
    1. No chain of references.
    2. If the object overrides the Finalize () method, it must be executed.
  2. If Finalize () restores the reference chain of objects, it can avoid being recycled.
  3. Finalize () of each object will be called by the system only once and only (it can be saved only once by this method).
  4. The virtual machine calls the thread to execute the Finalize () method, and it does not promise to wait for the finalize() method to end, so that the garbage collection mechanism can be hindered by slow execution of the method or even an infinite loop.
  5. Finalize () method not recommended!
    • High operating cost
    • Great uncertainty
    • The order in which objects are called cannot be guaranteed

Recovery method area

  1. Permanent generation garbage collection has two main parts:
    1. Deprecate constants: Determine whether constants are referenced and recycle them in a manner similar to Java heap garbage collection.
    2. Useless classes: A class must meet all three of the following criteria to be considered useless:
      1. All instances of the class are recycled, that is, there are no instances of the class in the Java heap.
      2. The ClassLoader that loaded the class has been reclaimed.
      3. The java.lang.Class object corresponding to this Class is not referenced anywhere, and the methods of this Class cannot be accessed anywhere through reflection.
  2. A VM does not reclaim a useless class if it meets the three reclamation conditions.
  3. Scenarios that use a lot of ByteCode frameworks such as Radiant, dynamic proxy, CGLib, dynamically generated JSP, and frequent custom Classloaders such as OSGi require the virtual machine to have the ability to unload to ensure that the permanent generation does not overflow.

Garbage collection algorithm

Tag – Cleanup algorithm

  • Mark – Clear algorithm (most basic) : divided into “mark” and “clear” two stages.
  • There are two major shortcomings:
    • Efficiency problem: Both phases are inefficient.
    • Space problem: It is easy to generate a large number of discrete memory fragments.

Replication algorithm

  • Copy algorithm: divide the memory evenly into two pieces, using only one piece at a time. When one piece is used up, the current surviving objects are copied to the other piece of memory (achieve neat arrangement effect), and then directly clean up the current whole piece of memory (high efficiency).
  • Main deficiency: the memory average points, the cost is too big.
  • Today’s commercial virtual machines use this method to reclaim the new generation, but because a large number of objects are reclaimed, the pre-reclaimed (Eden) and post-reclaimed (Survivor) regions are not equal, usually 8:1. If the Survivr region runs out of memory, guarantees are allocated to older ages.

Tag – Collation algorithm

  • Mark – Collation algorithm: mark, move the living object to one end, and then clean up memory beyond the boundary.
  • Used for all objects are alive extreme phenomenon, and full use of memory, suitable for the old age.

Generational collection algorithm

  • Generation collection algorithm: Divides the memory into several blocks according to the lifetime of objects. Then select the appropriate collection algorithm according to the characteristics of each era.
  • Current business virtual machines use a “Generational Collection” algorithm.

HotSpot algorithm implementation

Enumeration root node

  1. In accessibility analysis, many applications have very large method areas, and checking references one by one can be time-consuming.
  2. The sensitivity of the reachability analysis heap execution time is also reflected in GC pauses, as this analysis must be done in a snapshot to ensure consistency — all Java execution threads must be paused while GC is in progress.
  3. The virtual machine does not need a leakproof checking GC Roots, and there should be a way to know directly where object references are stored.

Safety point (Safepoint)

  1. HotSpot only generates oOPMaps at specific locations, called safe points, and pauses to perform GC.
  2. There are two scenarios for getting all threads to a safe point for GC:
    • Preemptive interrupt: When GC occurs, all threads are interrupted and threads that have not reached the safe point are allowed to resume until they all reach the safe point.
    • Active interrupt: A flag is set, and each thread actively polls this flag, and if it finds an interrupt flag, it actively stops. The mark overlaps with the safety point.

Safe Region

  1. Problem: If the program does not allocate CPU time, it cannot reach the safe point to suspend in a short time. It is not practical for the virtual machine to wait for this thread.
  2. A security zone is a code fragment in which reference relationships do not change.
  3. When the JVM initiates a GC, the thread in the safe zone is ignored. When the thread leaves the safe zone, it checks to see if the JVM has completed the root node enumeration process and then leaves.

Garbage collector

  • There is no best collector, no universal collector, only the most appropriate collector for specific applications.

Serial collector

  1. The Serial collector is the most basic and oldest in development.
  2. Serial collects the new generation using a copy algorithm and the old generation using a mark-collation algorithm.
  3. While the Serial collector is garbage collecting, it must suspend all other worker threads until the collection is complete.
  4. What Serial has over other collectors: simplicity and efficiency.
  5. It is still the default generation collector for virtual machines running in Client mode.

ParNew collector

  1. The ParNew collector is a multithreaded version of the Serial collector, using the same collection algorithm as Serial.
  2. In addition to the Serial collector, only the ParNew collector currently works with the CMS collector. (The ParNew collector is the preferred next-generation collector for many virtual machines running in Server mode.)

Parallel avenge

  1. The Parallel Scavenge collector is similar to the ParNew collector, but with a different emphasis.
  2. The goal of the Parallel Scavenge collector is to achieve controlled throughput (throughput = time to run user code/(time to run user code + garbage collection)). The Parallel Avenge collector is also known as a “through-first” collector because of its affinity for throughput.
  3. The Parallel Exploiter
    1. Parameters that control the maximum garbage collection pause time: The collector will try to limit completion to this time. (If this parameter is too small, throughput may be sacrificed.)
    2. Parameter that controls throughput size: This parameter is equivalent to the reciprocal of throughput.
    3. Control memory adaptive switch: After this parameter is enabled, the VM collects performance monitoring information based on the current system running status and dynamically adjusts the size of each memory area to provide the most appropriate pause time or maximum throughput. This adjustment mode is called GC adaptive adjustment policy. (The GC adaptive adjustment strategy is an important difference between the Parallel Scavenge collector and the ParNew collector.)

Serial Old collector

  1. The Serial Old collector is an older version of the Serial collector, which is also a single-threaded collector.
  2. Use the tag – collation algorithm
  3. It has two main uses:
    1. Use with the Parallel insane collector prior to JDK1.5.
    2. As a successor to CMS, used when Concurret Mode Failure occurs concurrently.

Parallel Old collector

  1. The Parallel Old collector is an older version of the Parallel Avenge collector.
  2. Use the mark-tidy algorithm.
  3. Mainly used with the new generation collector Parallel Scavenge.

CMS collector

  1. The CMS collector is a collector whose purpose is to obtain the shortest collection time.
  2. The CMS collector is based on a mark-delete algorithm.
    1. Initial tag: Marks objects that can be directly associated with GC Roots.
    2. Concurrent marking: The process of GC Roots Tracing.
    3. Relabelling: Corrects the marking record of the part of the object whose mark changed during concurrent marking because the user program continued to operate.
    4. Concurrent remove
  3. Three disadvantages of the CMS collector
    1. The CMS collector is very sensitive to CPU resources.
    2. The CMS collector is temporarily unable to handle floating garbage, and another Full GC may occur due to a “Concurrent Mode Failure”.
    3. The collection algorithm may generate a large amount of debris space.
      1. One switch parameter (on by default) : enable memory fragmentation when Full GC is generated. The process cannot be concurrent and the wait time becomes longer.
      2. One parameter: This parameter is used for the number of uncompressed Full GC followed by one compressed GC.
  4. G1 collector
    1. The G1 collector is one of the most advanced developments in collector technology today.
    2. The G1 collector is a garbage collector for server applications. Compared with other collectors, it has the following characteristics:
      • Parallelism and concurrency
      • Generational collection
      • Spatial integration
      • Predictable pauses: The G1 collector can model predictable pause times.
    3. G1 collector divides the Java heap into multiple equal independent regions (regions). G1 tracks the value of garbage accumulation in each Region and maintains a priority list in the background. According to the allowed collection time, the Region with the highest value is prioritized to improve collection efficiency.

Understanding GC Logs

I still don’t understand it. It’s on page P89…

Summary of garbage collector parameters

  • Book pages 90-91…
  • I still don’t know where these parameters are set…

Memory allocation and reclamation policies

The automatic memory management advocated in the Java technology architecture ultimately boils down to solving two problems automatically: allocating memory to objects and reclaiming memory allocated to objects.

Objects are allocated in Eden 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.
    • Minor garbage collection (GC) : Garbage collection in the new generation, usually at a fast speed.
    • Major GC(Full GC): Garbage collection that occurs in older generations and is more than 10 times slower than the New generation GC.

Big object goes straight to the old age

  • Large objects: Objects that require a large amount of contiguous memory.
  • One parameter: allows objects larger than this parameter value to be allocated directly in the old age. It avoids the large amount of memory replication that occurs during the replication algorithm.

Long-lived objects will enter the old age

  • The virtual machine defines an object age counter for each object. If the object is still alive after Eden is born and passes through the first Minor GC and can be accommodated by a Survivor zone, the object is moved to a Survivor zone and its age is increased by one year.
    • One parameter: If the age is greater than this parameter, the object enters the old age.

Dynamic object age determination

  • If the combined size of all objects of the same age in the Survivor space is greater than half of the size of the Survivor space, then objects older than or equal to the changed age can directly enter the old age without reaching the specified 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 is true, then Minor GC is guaranteed to be safe. Otherwise, the VM checks whether the guarantee failure is allowed (a switch parameter). If yes, the VM checks whether the maximum continuous available space of the old age is greater than the average size of the objects that have been promoted to the old age. If yes, a Minor GC is attempted, but this Minor GC is risky. If less than, or the virtual machine does not allow risk, a Full GC is performed instead.
  • After JDK 6 Update 24, this parameter is invalid and the VM is enabled by default.

Vm performance monitoring and troubleshooting tool

When locating problems for a system, knowledge and experience are the key basis, data are the basis, and tools are the means of using knowledge to process data.

JDK command line tools

  1. JPS: tool for vm process status
  2. Jstat: a tool for checking VM statistics
  3. Jinfo :JAVA configuration information tool
  4. Jmap :JAVA memory mapping tool
  5. Jhat: tool for analyzing dumped VM snapshots
  6. Jstack: JAVA stack tracing tool
  7. HSDIS:JIT generated code disassembly

JDK visualization tools

JConsole:Java monitoring and management console

VisualVM: All-in-one fault handling tool

Tuning case analysis and practice

  • Fuck, if I could read it, I…

Virtual machine execution subsystem

The transition from native machine code to bytecode as a result of code compilation is a small step in the development of storage formats, but a giant leap in the development of programming languages.

Class file structure

//TODO’s complex content needs to be perused and digested later. — Wowzki Shoede

Vm class loading mechanism

An overview of the

  1. The virtual machine loads the data describing the Class from the Class file to the memory, verifies, transforms, and initializes the data, and finally forms Java types that can be directly used by the VIRTUAL machine. This is the Class loading mechanism of the Java machine.

The timing of class loading

  1. The entire life cycle of a class consists of seven phases: load, validate, prepare, parse, initialize, use, and unload. Verification, preparation and analysis are referred to as links.
  2. The VIRTUAL machine specification is very strictOne and onlyThere are five cases where a class must be “initialized” immediately:
    1. When you encounter four bytecode instructions — New, getStatic, putstatic, or Invokestatic — you need to trigger initialization if the class is not initialized.
    2. When a reflection call is made to a class using the java.lang.Reflect package’s methods, initialization needs to be triggered if the class has not already been initialized.
    3. When initializing a class, if the parent class has not been initialized, the initialization of the parent class must be triggered first.
    4. When a virtual machine starts, the user specifies a primary class to execute. The virtual machine initializes this class first.
    5. JDK7 features, I do not understand, and very long, do not want to hit……
  3. Several scenarios:
       public void static main(String[] args){
           SuperClass[] sca = new SuperClass[10];
       }
    Copy the code
    1. Declare an array: The virtual machine does not trigger the initialization phase of the SuperClass, but starts the initialization phase of another class, which represents a one-dimensional array of properties and methods in the SuperClass. This class checks to see if the array is out of bounds.
        public class ConstClass{
        
            static{
                System.out.plintlin("ConstClass init!");
            }
            
            public static final String HELLOWORLD = "hello world";
        }
        
        public class NotInitialization{
            public void static main(String[] args){ ConstClass.HELLOWORLD; }}Copy the code
    1. This code doesn’t say “ConstClass init!” . This constant value has been stored in the constant pool of the NotInitialization class since constant propagation optimization was implemented during the cheap phase. Subsequent references from NotInitialization to constClass. HELLOWORLD are actually converted to references from the NotInitialization class to its own constant pool.
  4. Interface loading is a bit different from class loading. Interfaces also undergo initialization. The compiler generates a “()” class constructor for the interface, which initializes the member variables defined in the interface.
    • The initialization of an interface is accompanied by the initialization of the class that implements it. The parent interface is not necessarily initialized, but is only initialized when the parent interface is actually used.

The process of class loading

  • Load, verify, prepare, parse, initialize these five stages of specific actions.

loading

  1. During the “load” phase, the VM does three things:
    1. Gets the binary byte stream of a class by its fully qualified name.
    2. Transform the static storage structure represented by this class into a data structure for the method area runtime.
    3. 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.
  2. The “load” phase can be accomplished either using the system-provided boot class loader or by a user-defined class loader.
  3. In the case of arrays, the array classes themselves are not created by the classloader, but are created directly by the Java Virtual machine. The creation process follows the following rules:
    1. If the array component is a reference type, the component type is first loaded using a classloading mechanism. The array is identified in the class namespace of the classloader that loaded the component type. (Question: If the component type is loaded, why is the array class not loaded in the code above?)
    2. If the component type is a primitive type, the Java virtual machine marks the array as associated with the boot class loader.
    3. The visibility of array types is the same as that of component types, which default to public if they are not reference classes.
  4. Parts of the load and join phases intersect, but the order in which they begin execution is fixed.

validation

  1. The 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.
  2. The verification can be roughly divided into four stages:
    1. File format verification: Byte streams conform to the Class file specification and can be processed by the current version of the Java virtual machine.
    2. Metadata validation: Semantic analysis of the information described by bytecode to ensure that the information described conforms to the requirements of the Java language specification.
    3. Bytecode verification: mainly through data flow and control flow analysis, to determine whether the program semantics are legal and logical. After the metadata’s data type is validated in the second phase, the class’sMethod bodyVerify and analyze to ensure that you do not compromise the security of virtual machines.
      • Even if a program passes bytecode verification, it is not safe to say that the program can not be verified with absolute accuracy.
    4. Symbolic reference validation: Converts symbolic references to direct references. This transformation takes place during the parse phase.
  3. The validation phase is a very important, but not necessarily necessary, phase for the virtual machine’s classloading mechanism (it has no impact on program runtime).
    1. A switch parameter: used to turn off most of the class validation measures and reduce class loading time.

To prepare

  1. The preparation phase is the formal allocation of memory for class variables and the setting of their initial values (which generally mean zero, not the values specified in the code). The memory used by these variables is allocated in the method area.
  2. Special case: If a class field property has a ConstantValue property in the property table (static, final, basic type, or String), the field is initialized to the value specified by the code during preparation.
public static final int value = 123;
Copy the code

parsing

  1. The parsing phase is the process by which the virtual machine replaces symbolic references in the constant pool with direct references.
    • Symbolic references: Symbolic references describe the referenced object as a set of symbols.
    • 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.
  2. Multiple parse requests for the same symbolic reference are common, and virtual machine implementations can cache the results of the first parse. (Except invokedynamic instructions)
  3. This rule does not hold for invokedynamic instructions. The reference to this is called the “dynamic call point qualifier,” where “dynamic” means that the parsing action cannot be executed until the program actually runs to this instruction.
  4. The parse action is mainly for class or interface, field, class method, interface method, method type, method handle, and call point qualifier 7 class symbol references.
  5. Parse the four types of references:
    1. Class or interface resolution: Assuming the current code is of class D, if you want to resolve a symbolic reference N that has never been resolved into a direct reference to class or interface C.
      1. If C is not an array type, the virtual machine will pass the fully qualified name representing N to D’s classloader to load C. As soon as any exception occurs during the load process, the parsing process is declared a failure.
      2. If C is an array type and the element type of the array is an object, the array type is loaded as in point 1. The virtual machine then generates an array object that represents the dimensions and elements of the array.
      3. Check whether D has the access permission to C. If do not have, throw the Java. Lang. IllegalAceessError anomalies.
    2. Field resolution: Use C to represent the class or interface to which a field belongs. Vm specifications require the following steps to search for subsequent fields in C:
      1. If C itself contains a field whose simple name and field descriptor match the target, return a direct reference to that field, and the search ends.
      2. Otherwise, if an interface is implemented in C, each interface and its parent interface will be recursively searched from bottom to top according to the inheritance relationship. If the interface contains a field whose simple name and field descriptor match the target, the direct reference of the field will be returned, and the search ends.
      3. Otherwise, if C is not java.lang.Object, the parent class is recursively searched from bottom to top based on inheritance. If the parent class contains a field whose simple name and field descriptor match the target, a direct reference to the field is returned, and the search ends.
      4. Otherwise, find failure, throw the Java. Lang. NoSuchFieldError anomalies.
      5. If find successful return references, if do not have field access, it throws Java. Lang. IllegalAceessError anomalies.
    3. Class method resolution: Use C to represent the class or interface to which a field belongs. Vm specifications require that you perform the following steps to search for subsequent fields in C:
      1. Class method and symbolic constant reference types defined interface method is separate, if a class method table class_index index C is found in the interface, that is thrown directly Java lang. IncompatibleClassChangeError anomalies.
      2. If you pass the first step, look in class C to see if there is a method with a simple name and field descriptor that matches the target, return a direct reference to the method, and the search ends.
      3. Otherwise, the parent class of class C recursively looks for methods with simple names and field descriptors that match the target, returns a direct reference to the method, and the search ends.
      4. Otherwise, the class C implementation of the interface list and their parent interface of recursive search if there is a simple name, and the method of field descriptor is match the target, if there is the class C is an abstract class, then find the end, throwing Java. Lang. AbstractMethodError anomalies.
      5. Otherwise, announced the method to find the failure, throw Java. Lang. NoSuchMethodError anomalies.

Initialize the

  1. The initialization phase actually executes the Java program code defined in the class.
  2. The initial phase is the process of executing the class constructor () method.
    1. The () method is generated by the compiler automatically collecting all class variable assignments in a class and statement merges in a static statement block (static{}), in order determined by the order in which the source files appear.
    2. The () method, unlike the instance constructor, does not require an explicit call to the superclass constructor, and the virtual machine guarantees that the subclass’s () method will complete before the subclass’s () method executes.
    3. The () method is not required and will not be generated without a static block and class variable assignment.
    4. Interfaces also have () methods (which initialize assignments), but the interface’s () method is triggered only when the interface variable is called.
    5. The virtual machine ensures that a class’s () methods are properly locked and synchronized in multiple threads. A type is initialized only once by the same classloader.

Class loader

  1. Get the binary byte stream describing a class by its fully qualified name. The code module that does this is called the class loader.

Classes and class loaders

  1. For any class, its uniqueness within the Java virtual machine needs to be established both by the classloader that loads it and by the class itself, each with a separate class namespace.

Parental delegation model

  1. In terms of Java virtual machines, there are only two types of loaders:
    1. Bootstrap ClassLoader: this ClassLoader is implemented in C++ and is part of the virtual machine itself. Read the class libraries in the

      /lib directory.
    2. Other classloaders: Implemented in the Java language, independent of the virtual machine, and all inherited from the abstract java.lang.classloader class.

      /lib/ext Application ClassLoader: Reads the class libraries on the ClassPath.
  2. The parent delegate model requires that all class loaders have their own parent class loaders, except for the top-level start class loaders.
  3. Working process of parent delegation model: when a class loading request is obtained, it is first handed over to the parent class loader for loading. If the parent class loader fails to complete the loading request, the child child loader tries to load again.
  4. Benefits: Java classes have a hierarchy of priorities along with their classloaders.

Break the parent delegate model

//TODO has three destructions, anyway I can’t read……

Virtual machine bytecode execution engine

An overview of the

  1. The execution engine is one of the most core components of the Java Virtual machine.

Run time stack frame structure

  1. A Stack Frame is a data structure for virtual machine method invocation and method execution. It is the Stack element of the virtual machine Stack in the data area when the virtual machine runs. The stack frame stores the method’s local variator, operand stack, dynamic linkage, method return address, and some additional information.
  2. For the execution engine, only the stack frame at the top of the stack is valid in an active thread, called the current stack frame. All bytecode instructions run by the execution engine operate only on the current stack frame.

Local variable scale

  1. Local Variable Table is a set of Variable value storage space used to store method parameters and Local variables defined within a method. When the Java program is compiled as a Class file, the max_locals data item of the method’s Code property determines the maximum size of the local variable table that the method needs to allocate.
  2. The smallest unit of the local Variable scale is the Variable Solt.
  3. The virtual machine uses the local variable table by indexing. The value ranges from 0 to the maximum number of solts in the local variable table.
  4. During method execution, Solt with index value of 0 is used to store references to instances of the method, Solt with index value of 1 is used to sequential out the parameters of the storage method, and the remaining Solt stores local variables within the method.
  5. To save space for stack frames, the virtual machine allows reuse of Solt. When a method variable is known to be out of scope by the PC count, the Solt of that local variable is handed over to other variables.
  6. Local variables cannot be used without an initial value (without going through the initialization phase).

Dynamic connection

  1. Each stack frame contains a reference to the method that the stack frame belongs to in the runtime constant pool, and this reference is held to support dynamic concatenation during method calls.
  2. Symbolic references that are converted to direct references at compile time are static resolution, and those that are converted to direct references at run time are dynamic concatenation.

Method return address

  1. There are only two ways to exit a method after it executes.
    1. Normal completion exit: When the execution engine encounters a bytecode instruction returned by any method, there may be a return value passed to the upper method caller, depending on the return instruction
    2. Exception completion exit: Another exit in which method execution encounters an exception that is not handled within the method, causing the method to exit.
    3. When a method exits normally, the value of the caller’s PC counter can be used as the return address, and it is likely to be stored in the stack frame. When an exception exits, the return address is determined by the exception handling table, and the stack frame generally does not store this information.

Additional information

  • Virtual machines allow the implementation of a specific virtual machine to add descriptions to the stack frame that do not exist in the specification.
  • Dynamic connections, method return addresses, and other additional information are generally grouped together as stack frame information.

The method call

  1. Method invocation is not equal to method execution. The only task of method invocation stage is to determine the version of the called method (determine which method to call), which temporarily does not involve the specific running process inside the method.

parsing

1. The target methods of the method call are symbolic references in a constant pool in the Class file, some of which are converted to direct references during the parsing phase of the Class load. 2. The above resolution is valid if: the call target must be determined when the program code is written and the compiler compiles. The invocation of this class method is called parsing. 3. The Java language’s “know at compile time, run time immutable” methods are mainly static and private. 4. The Java VM provides five methods to invoke bytecode commands: + Invokestatic + Invokespecial