This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Abstract:

Java developers often encountered in the application of Java. Lang, a ClassNotFoundException this exception, the exception behind Java knowledge is what we want to do today, the theme of the Java class loading mechanism.


I. Five processes of loading

The JVM class loading mechanism is divided into five parts: load, validate, prepare, parse, and initialize. Here’s a look at how the JVM handles class loading in these five ways.

1, load,

Loading is the phase of the Class loading process that generates a java.lang.Class object in memory that represents the Class and acts as an entry point to the Class’s various data in the method area. Note that this does not have to be obtained from a Calss file, but can be read from a zip package (JAR, WAR), computed dynamically at run time (dynamic proxy), or generated by another file (JSP file installed into the corresponding Class Class).

2, validation,

The main purpose of the verification phase is to ensure that the information contained in the byte stream of the Class file meets the requirements of the current VIRTUAL machine and does not harm the security of the virtual machine.

3, preparation,

The preparation phase is the phase that formally allocates memory for class variables and sets their initial values, that is, the memory space used by these variable locks is allocated in the method area. A brief explanation of initial assignment of class variables is required.

The put static instruction that assigns A value of 1998 to A is stored in the class constructor <client> method after the program is compiled. public static int A = 1998; Public static final int B = 1998 public static final int B = 1998Copy the code

4, parsing,

The parsing phase is when the virtual machine replaces symbolic references in the constant pool with direct references. Symbolic references are in the class file:

  • CONSTANT_Class_info
  • CONSTANT_Field_info
  • CONSTANT_Method_info

Constants of the same type.

4.1 Symbol Reference

Symbolic references are independent of the layout implemented by the virtual machine, and the target of the reference does not have to be loaded into memory. The memory layout of various virtual machine implementations can vary, but the symbolic references they accept must be consistent, so the literal form of symbolic references is explicitly defined in the Class file format of the Java Virtual Machine specification.

4.2 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. If there is a direct reference, the target of the reference must already exist in memory.

5. Initialization

The initialization phase is the last phase of class loading, and after the previous class loading phase, processing is dominated by the JVM except for the customization of the class loader during the loading phase. During the initialization phase, the Java program code defined in the class is actually executed.

5.1 Class constructor

The initialization phase is the process of executing the class constructor methods. Methods are a combination of assignment operations that the compiler automatically collects for class variables in a class and statements in a static statement block. The virtual machine guarantees that the methods of the parent class are executed before the child methods are executed. If there are no static variable assignments and no static code blocks in a class, the compiler may not generate methods for that class.

Note that class initialization is not performed in several cases:

  • A reference to a static field of a parent class by a subclass only triggers initialization of the parent class, not the subclass
  • Defining an array of objects does not trigger initialization of the class
  • Constants are stored in the constant pool of the calling class at compile time. There is no direct reference to the class in which the constant is defined, and the class in which the constant is defined is not triggered.
  • Fetching a Class object by its name does not trigger Class initialization.
  • If initialize is false, Class initialization is not triggered when a Class is loaded via class.forname. This parameter tells the vm whether to initialize the Class.
  • Initialization is also not triggered by the default loadClass method of a ClassLoader.

\

Class loaders

The virtual machine design team implements class loading actions outside the JVM so that the application can decide how to get the classes it needs. The JVM provides three types of loading

2.1 Starting the BootStrap ClassLoader

Responsible for loading classes in the JAVA_HOME\lib directory, or in the path specified by the -xbootCLASspath parameter, and recognized by the virtual machine (by filename, such as rt.jar).

2.2 Extension ClassLoader

Is responsible for loading classes in the JAVA_HOME\lib\ext directory, or class libraries in the path specified by the java.ext.dirs system variable.

2.3 Application ClassLoader

Responsible for loading class libraries on the user’s classpath.

Parent delegation model

The JVM does class loading through the parent delegate model, and of course we can implement custom class loaders by inheriting java.lang.ClassLoader. The specific process of parental delegation: When a class receives a classload request, it first does not attempt to load the class itself. Instead, it delegates the request to its parent class. This is true of every hierarchical classloader, so all load requests are passed to the starting classloader. Only when the parent Class loader feedback they can’t finish the load request (in this Class loader path not found the required loading Class), the loader subclass will try to load, adopting parents delegate benefit is that which loader to load a Class no matter use, eventually, in turn, delegate to start the Class loader and then step by step down to load, This ensures that different class loaders will end up with the same Object.

\

4. Problems with class loading mechanism

4.1 Class version Conflict

When different versions of the same class exist on the classpath, if the classloader finds one version, it will no longer search to load the other version.

4.2 Dependencies between Jars cannot be determined

Existing JAR in the standard lack of support for dependencies between the JAR file, so only at run time can’t find the class, you need to be thrown. Java lang. ClassNotFundException abnormalities, the runtime exception, is very unfriendly to developers.

4.3 Information Hiding

If a JAR is on the classpath and loaded, then all the public classes in the JAR will be loaded. Some classes will not be loaded if they do not want to be loaded. Although the class loading mechanism has been improved in J2EE, war packages or EAR applications can be loaded as units. But the above problems have not been well solved.

4.4 Solutions

OSGi is a dynamic Java Module system that specifies how a Module is defined and how those modules interact with each other. Each OSGi Java module is called a bundle. Each bundle has its own classpath that specifies exactly which Java packages and classes can be exported, which classes and packages from which other bundles need to be imported, and which dependencies between bundles are specified. In addition, bundles can be installed, updated, and uninstalled at runtime without affecting the entire application. In this way, the hierarchical class loading mechanism becomes a mesh class loading mechanism. Before the application starts, OSGi can detect whether all dependencies are satisfied and, if not, pinpoint which ones are not.

Five, the OSGI

5.1 introductionOSGI Baidu Encyclopedia

OSGI(Open Service Gateway Initiative) is a dynamic model system for Java. It is a series of specifications for Java dynamic modular system.

5.2 Dynamically changing the structure

The OSGI service platform provides the ability to dynamically change constructs on a variety of network devices without a restart. To minimize and make these couplings manageable, OSGI technology provides a service-oriented architecture that enables these components to discover each other dynamically.

5.3 Modular Programming and Hot Swap

OSGI is designed to provide the foundation for modular programming of Java programs. Osgi-based programs may be hot-pluggable at the module level, enabling only deactivating, reinstalling, and then launching parts of the program when it is updated, which is a very attractive feature for enterprise development.

OSGI describes a beautiful goal of modular development, identifies the services and architectures needed to achieve this goal, and has mature framework implementation support. But not all applications are suited to OSGI as an infrastructure. While it provides power, it introduces additional complexity because it does not follow the parent-delegate model of class loading. (This technology is not mainstream now, RPC is!)