1 What is the JVM

There’s a lot of official talk on the Web about what a JVM (Java Virtual Machine) is. In short, the main reason JAVA code can be written once and run anywhere is because of the JVM. It shields operating system-specific information so that JAVA programs simply generate bytecode instructions on the JVM that the JVM can execute, and the JVM interprets these bytecode instructions as machine instructions that the operating system can execute.

2 JDK, JRE, and JVM

**JDK(Java Development Kit)** : Provides Java program developers to operate the Development Kit.
**JRE(JavarRuntime Environment)**, the platform on which Java programs run, the place where Java programs run
**JVM(Java AvirtualMachine)** is part of the JRE. Virtual computer, so that Java programs and operating system isolation, achieve platform independence.

3 Java code compilation

A.java file is compiled into a.class file by the Java source compiler. The compilation process is as follows:
.java file -> Lexical Parser -> Tokens Flow -> Parser -> Syntax Tree/Abstract Syntax Tree -> Semantic Parser
Annotation abstract syntax tree -> bytecode generator ->.class file.
The generated file contains the following information:
  • Structural information: Includes information about the class file format, version number, number and size of sections
  • Metadata: Information corresponding to declarations and constants in Java source code. Contains declaration information, domain and method declaration information, and constant pool for class/inherited superclass/implemented interfaces
  • Method information: Information that corresponds to statements and expressions in the Java source code. Contains bytecode, exception handler table, evaluation stack and local variable area size, evaluation stack type record, debug symbol information.

Class loading mechanism

4.1 Load

Find and import class files
  • The ClassLoader gets the binary stream that defines a class by its fully qualified name
  • Convert the static storage structure represented by this byte stream to the data structure of the method area runtime
  • A class object representing this class is generated in the heap as an entry point to the method area data

4.2 Links

4.2.1 Verify

  • File format validation
  • Metadata validation
  • Bytecode verification
  • Symbolic reference verification

4.2.2 Prepare

Allocates memory for static variables and initializes default values for them

4.2.3 Parsing (Resovle)

Converts symbolic references in a class to direct references
Symbol references: class files such as super_class, interface_class,fields_count, etc.
Direct reference: Memory address, offset, that points directly to the target.
ClassFile {
 u4       magic;
 u2       minor_version;
 u2       major_version;
 u2       constant_pool_count;
 cp_info    constant_pool[constant_pool_count-1];
 u2       access_flags;
 u2       this_class;
 u2       super_class;
 u2       interfaces_count;
 u2       interfaces[interfaces_count];
 u2       fields_count;
 field_info   fields[fields_count];
 u2       methods_count;
 method_info  methods[methods_count];
 u2       attributes_count;
 attribute_info attributes[attributes_count];
}
Copy the code

4.3 Initialization

Performs initialization on a static variable of a class, a static code block

Class loader

5.1 classification

  1. Bootstrap ClassLoader loads all jar packages specified by class or Xbootclassoath in jre/lib/rt.jar in $JAVA_HOME. Implemented by C++, not a ClassLoader subclass.
  2. Extension ClassLoader Loads some Jar packages of Java platform Extension functions, including jre/lib/*. Jar in $JAVA_HOME or Jar packages in -djava.ext. dirs.
  3. App ClassLoaderj loads the jars specified in the classpath and the classes and jars specified in the java.class.path directory.
  4. The Custom ClassLoader uses a subclass of java.lang.ClassLoader to customize classes. For example, Tomcat and JBoss implement ClassLoader according to J2EE specification.

5.2 Parent delegation mechanism

When a classloader needs to load a.class file, it first delegates the task to its parent classloader, recursively working its way up to the top. If the parent class is not loaded, you will load it yourself.
protected Class loadClass(String name, Boolean resolve) throws ClassNotFoundException {synchronized (getClassLoadingLock(name)) {// First check if the Class has been loaded findLoadedClass(name); // c==null if (c ==null) {long t0 = system.nanotime (); Try {// If there is a parent class loader, if there is a parent class loader, the recursive operation if (parent! = null) { c = parent.loadClass(name, false); C = findBootstrapClassOrNull(name); c = findBootstrapClassOrNull(name); } } catch (ClassNotFoundException e) { // ClassNotFoundException thrown if class not found // from the non-null parent Class long t1 = system.nanotime (); if (c == null) {// If (c == null) {class long t1 = system.nanotime (); c = findClass(name); // this is the defining class loader; record the stats sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); sun.misc.PerfCounter.getFindClasses().increment(); } } if (resolve) { resolveClass(c); } return c; }}Copy the code

Functions: 1, prevent the repeated loading of a. Class.
2. Ensure that the core. Class file is not tampered with.

The runtime data area of the JVM

In step 2,3 of the load, there are references to heap, method area, etc. Let’s focus on the layout of the run data area.
About the official website: [https://docs.oracle.com/javase/specs/jvms/se8/html/index.html](https://docs.oracle.com/javase/specs/jvms/se8/html/index .html)
The Java Virtual Machine defines various run-time data areas that are used

during execution of a program. Some of these data areas are created on Java

Virtual Machine start-up and are destroyed only when the Java Virtual Machine

exits. Other data areas are per thread. Per-thread data areas are created when a

thread is created and destroyed when the thread exits.

6.1 Method Area

A method area is an area of memory shared by individual threads that is created when the virtual machine is started.
It is used to store information about classes loaded by the virtual machine, constants, static variables, code compiled by the just-in-time compiler, and so on
Although the Java Virtual Machine specification describes the method area as a logical part of the Heap, it is also known by the nickname non-heap to distinguish it from the Java Heap.
OutOfMemoryError is thrown when the method area cannot meet memory allocation requirements
Note: The method area is Metaspace in JDK8 and Perm Spacel in JDK6 and 7.
The runtime constant pool is allocated in the method area to hold literals and symbolic references generated at compile time

6.2 Heap

Thread sharing is also created when the VM is started
Java object instances and arrays are allocated on it

6.3 Java Virtual Machine Stacks

Thread private, which holds the call state of a method in a thread
Each method executed by a thread is a stack frame in that stack, i.e. each method corresponds to a stack frame.
Calling a method pushes a stack frame onto the stack; When a method call completes, the stack frame is ejected from the stack.

6.4 The PC Register

A JVM process has multiple threads executing, and the execution rights of the threads depend on the CPU. When thread A gets somewhere, it loses the execution rights of the CPU, switches to thread B, and then when thread A gets the execution rights of the CPU again, how can it go back to where it left off? This requires maintaining a variable in the thread that records where the current thread is executing
Program counters are designed to solve the problem of switching between threads to recover to the correct execution position. Each thread has a separate program counter (thread private).

6.5 Native Method Stacks

The local method executed by the current thread
public native int getInt(Object var1, long var2);
public native void putInt(Object var1, long var2, int var4);
Copy the code