1. Class loading
The JAVA code we are writing is compiled through Javac into a class file called bytecode. The JVM loads it and interprets it as machine code execution. The process by which the JVM loads a class file is called loading. In JDK1.8, class information is loaded into the meta space. When we create objects based on the corresponding class, this is the end product of the class.
2. The loading process of classes
- Loading stage
When information about a class is used (for the first time) in code, the corresponding class is loaded into memory from the corresponding “.class “bytecode file.
- Validate, prepare, parse, initialize
Validation: Verifies that the contents of the “. Class “file you loaded in conform to JVM specifications
Preparation: Allocate memory space to class space, allocate memory space to class variable (static) modifier
Parsing: The parsing phase replaces symbolic references with direct references. Parsing can occur either before initialization (static parsing) or after initialization (dynamic parsing, such as polymorphism, late binding).
Initialization: The initialization phase is the process of executing the class’s constructor method clinit(). This method requires no definition and is a combination of the statements in the static code block and the assignment actions of all class variables automatically collected by the Javac compiler. The clinit() instructions are executed in sequence according to the code’s statement order, and the virtual machine must ensure that a class’s Clinit () methods are locked synchronously across multiple threads. There are two main steps: assign a value to a class variable; Execute a static code block.
Class loader and parent delegate mechanism
Now that we’ve looked at the classloading process, let’s take a closer look at the loader.
- Bootstrap ClassLoader: this loader is not a Java class, but is implemented by the underlying c++ and is responsible for loading the Jdk core class libraries (e.g. Rt.jar, resources.jar, charsets. Jar, etc.) and the two class loaders after loading. This ClassLoader is completely controlled by the JVM itself. The JVM controls which classes need to be loaded and how they are loaded. No one else can access this class.
- Extension ClassLoader: a common Java class that inherits from the ClassLoader class. It is responsible for loading all jar packages in {JAVA_HOME}/jre/lib/ext/.
- Application loader: Is a child object of the Extension ClassLoader that loads all jar and class files in the application’s classpath directory.
- Custom class loaders: Custom class loaders to load your classes according to your own needs
- Parental assignment: If your application class loader needs to load a class, it will delegate it to its parent class loader and eventually pass it on to the top-level class loader
But if the parent class loader does not find the class in its own area of responsibility, it will push down the loading rights to its own subclass loader.