Class loading process

Loading->Linking(verification->preparation->resolution)->Initializing

Loading

Load the.class file into memory

Linking

  1. Verification: Verifies that the file complies with JVM specifications
  2. Static member variables are assigned default values
  3. Resolution: Resolves symbolic references to classes, methods, and attributes into direct references, and various symbolic references in the constant pool into direct references to Pointers, offsets, and other memory addresses

Initializing

Call the class initialization code to assign initial values to static member variables

ClassLoader

Description: If CustomClassLoad has not been loaded, go to AppClassLoad. If CustomClassLoad has not been loaded, go to AppClassLoad. If CustomClassLoad has not been loaded, return AppClassLoad. Then, if it’s not loaded by itself, find the class and load it. If it’s not loaded by itself, find the class until it’s loaded by ClassLoad. If it’s not loaded, raise a notfoundClass exception.

Loading

  1. Parental delegation, mainly for security reasons
  2. Five cases of LazyLoading
    1. The new getstatic putstatic Invokestatic directive, except to access final variables
    2. When java.lang.Reflect makes a reflection call to a class
    3. When a child class is initialized, the parent class is initialized first
    4. When the virtual machine starts, the main class to be executed must be initialized
    5. Dynamic language support Java. Lang. Invoke. Analytical results for MethodHandle REF_getstatic REF_putstatic REF_invokestatic method handles, the class must be initialized
  3. FindInCache -> parent. LoadClass -> findClass()
  4. Custom class loaders
  5. Mixed execution compile execution explain execution

Linking

I will use a small program to illustrate the loading process of a class

public class ClassLoadingDemo{
    public static void main(String[] args) {
        System.out.println("count:"+T.count);
    }
}

class T {
    public static int count = 2; //0
    public static T t = new T(); // null


    private T() {
        count ++;
           }
}

// count:3
Copy the code

Why is count equal to 3 here? Because instantiation usually has a process of opening up space, and then on assignment, first int count =0,T T =null, and then on initialization int cout =2, T instantiation calls the constructor that does count++, so it prints count:3, so if I go through this code, Let’s analyze for ourselves what is the print result

public class ClassLoadingDemo{ public static void main(String[] args) { System.out.println("count:"+T.count); } } class T { public static T t = new T(); // null public static int count = 2; //0 private T() { count ++; }}Copy the code

JMM Java memory model

Hardware-level cache consistency (cache lock MESI)

Cache lines and pseudo-sharing. Generally, when the CPU executes, it takes data piece by piece, and unused data will also be taken over. It is possible that multiple cpus will compete with each other when using a cache line, and cache failure will affect performance. But, some problems that cannot be cached or solved by MESI must still be locked

MESI Cache consistency protocol

Agreement (msci) : www.cnblogs.com/z00377750/p…

Status in the MESI protocol

Each cache line in the CPU is marked with four states (represented by an extra two bits)

M: Modified

The cache line is only cached in that CPU’s cache and is dirty, that is, inconsistent with the data in main memory. The memory in this cache line needs to be written back to main memory at some future point before it can be read by other cpus. When written back to main memory, the state of the cache row becomes exclusive.

E: Exclusive

The cache row is only cached in that CPU’s cache, it is unmodified, consistent with the data in main memory, and the state can become shared at any time when the memory is read by another CPU. Again, it can be Modified. The state becomes Modified.

S: Shared

This state means that the cache row may be cached by more than one CPU, and the cache row data is consistent with main memory. If one of the cache rows is modified, the other CPU cache states become Invalid

I: Invalid

The cache is invalid (other cpus may have modified the cache line).

Cache line

The larger the cache line is, the higher the local space efficiency is, but the lower the read efficiency is. The smaller the cache line is, the lower the local space efficiency is, but the higher the read efficiency is.

Out-of-order problem

CPU in order to improve the efficiency of instruction execution, will be in the process of an instruction execution (such as going to a memory read data (100 times slower)), to the execution of another at the same time, the premise is that two instructions without dependency on www.cnblogs.com/liushaodong… Write operations have the concept of merge write, WCBuffer. Merge write operations may also be out of order, because some write operations are fast and some write operations are slow. Generally there are only 4 positions (especially valuable, rare items) in batch scenarios, we can use WCbuffer to improve the efficiency of the program.

How to prove the out-of-order problem

public class T04_Disorder { private static int x = 0, y = 0; private static int a = 0, b =0; public static void main(String[] args) throws InterruptedException { int i = 0; for(;;) { i++; x = 0; y = 0; a = 0; b = 0; Thread one = new Thread(new Runnable() { public void run() { a = 1; x = b; }}); Thread other = new Thread(new Runnable() { public void run() { b = 1; y = a; }}); one.start(); other.start(); one.join(); other.join(); String result = "first" + I + "time (" + x +", "+ y +") "; if(x == 0 && y == 0) { System.err.println(result); break; } else { //System.out.println(result); } } } public static void shortWait(long interval){ long start = System.nanoTime(); long end; do{ end = System.nanoTime(); }while(start + interval >= end); }} the 218385th time (0,0)Copy the code

After executing the above code for a period of time, a 0,0 situation will appear, which is a good example of out-of-order execution.

How to ensure order

Hardware memory barrier X86
  1. Sfence (savefence) : Writes before the sfence directive must be completed before writes after the sfence directive.
  2. Lfence (loadfence) : Reads before the lfence directive must be completed before reads after the lfence directive.
  3. Mfence (mixfence) : Read and write operations before the mfence directive must be completed before read and write operations after the mfence directive.

Atomic instructions, such as “Lock…” on x86 The instructions are a Full Barrier that locks up the memory subsystem to ensure that they are executed sequentially, even across multiple cpus. Software Locks typically use memory barriers or atomic instructions to implement variable visibility and maintain program order such as Lock ADDL

How to regulate the JVM level (JSR133)
  1. LoadLoad barrier: for statements such as Load1; LoadLoad; Load2: Ensure that the data to be read by Load1 is completed before the data to be read by Load2 and subsequent read operations are accessed.
  2. StoreStore barrier: for statements like Store1; StoreStore; Store2. Before Store2 and subsequent write operations are executed, ensure that the write operations of Store1 are visible to other processors.
  3. LoadStore barrier: for statements such as Load1; LoadStore; Store2, ensure that the data to be read by Load1 is completed before Store2 and subsequent write operations are flushed out.
  4. StoreLoad barrier: for statements like Store1; StoreLoad; Load2, ensure that writes to Store1 are visible to all processors before Load2 and all subsequent reads are executed.

Volatile implementation details

Bytecode layer

ACC_VOLATILE

The JVM level

LoadLoad barrier, StoreStore barrier, LoadStore barrier, StoreLoad barrier

OS and hardware

Blog.csdn.net/qq_26222859… The lock instruction implement hsdis – HotSpot Dis Assembler Windows | msci implementation

Details of synchronized implementation

Bytecode layer

ACC_SYNCHRONIZED monitorenter —> monitorexit

The JVM level

C++ calls the synchronization mechanism provided by the operating system

OS and hardware

X86 : lock cmpxchg / xxx https://blog.csdn.net/21aspnet/article/details/88571740