Java Virtual machine class loading and memory structure

Source: Internet
Author: User

Http://www.jb51.net/article/105920.htm

Https://www.cnblogs.com/Qian123/p/5707562.html

Java class loading whole process

A Java file from being loaded to being unloaded in this life process has a total of 4 stages to go through:

Load-On (validate + prepare + Parse) initialization (pre-use preparation), use, uninstall

where loading (in addition to custom loading) + chaining is entirely the responsibility of the JVM, when to initialize the class (the Load + link has been done before), the JVM has strict rules (four cases):

1. When encountering the New,getstatic,putstatic,invokestatic 4 bytecode directive, the join class is not initialized yet, it is initialized immediately. In fact, there are 3 situations: when you instantiate a class with new, read or set the static fields of the class (not including the final modified static fields, because they are already plugged into the constant pool), and when the static method is executed.

2. When using the Java.lang.reflect.* method to make a reflection call to a class, if the class has not yet been initialized, do so immediately.

3. Initialize a class, if his father has not been initialized, first to initialize his father.

4. When the JVM starts, the user needs to specify a main class to execute (the class that contains the static void main (string[] args), the JVM initializes the class first.

The principle mechanism of Java to improve the--JVM loading class file

Read Catalogue

    • 1. Introduction to the JVM
    • 2. Components of the JVM
    • 3, the JVM load class file principle mechanism

In the interview with the Java engineer, this question is often asked, so special attention needs to be paid.

Back to top 1, JVM introduction

The JVM is the most basic foundation of our Javaer, when we first started to learn Java, we usually start with "Hello World", then write a complex point class, then find some open source frameworks, such as spring, Hibernate, etc. Then the development of enterprise-class applications, such as Web sites, enterprise applications, real-time trading system, and so on, until one day suddenly found that the system is so slow, and from time to time a memory overflow something, today is the trading system reported Stackoverflowerror, Tomorrow is the site system reported a outofmemoryerror, this error is difficult to reproduce, only the analysis of Javacore and dump files, good luck can also analyze a result, run the point, go directly to the temple incense! Every day to pick up the customer's phone is trembling, for fear of what a moth. I think Java has this experience for a long time, so where is the ultimate root knot of these problems? --JVM.

The JVM is the full name of Java Virtual machine, the Java VM, that is, the computer on a virtual computer, which is not the same as we use VMware, the virtual thing you can see, this JVM you are invisible, it exists in memory. We know that the basic composition of the computer is: the operator, controller, memory, input and output devices, the JVM is also a complete set of elements, the operator is of course, to the hardware CPU is also processed, just in order to adapt to "once compiled, run anywhere" situation, need to do a translation action, so the JVM Own command set, which is a bit like the assembly command set, each assembly command set for a series of CPUs, such as the 8086 series of the assembly can also be used in 8088, but cannot run on 8051, and the JVM command set can be run everywhere, because the JVM has been translated, Translate into different machine languages depending on the CPU.

The most profound thing we need to understand in the JVM is its storage part, storage. Hard disk? No, no, the JVM is an in-memory virtual machine, it's storage is memory, we write all classes, constants, variables, methods are in memory, which determines whether our program is robust, efficient, the next part is the focus of the introduction.

Back to top 2, part of the JVM

Let's first draw the JVM into this virtual machine, as shown in:

As you can see from this diagram, the JVM is running on top of the operating system, and it has no direct interaction with the hardware. Let's look at the components of the JVM, as shown in:

This diagram is a reference to the network's widely circulated JVM composition diagram, which is divided into four parts for the entire JVM:

# # class Loader ClassLoader

The role of the ClassLoader is to load the class file into memory, such as writing a Helloword.java program and then compiling it into a class file through Javac, how can it be loaded into memory to be executed? Class Loader is responsible for this, it is not possible to create a. class file can be loaded, class Loader loaded class file is a format requirement, in the "JVM specification" Chinese-style definition class file structure:

  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];    }

If you need to know more, you can read the fourth chapter "the Class File Format" in "JVM Specification", which is no longer explained in detail.

Friendly tip: Class Loader just load, as long as the file structure to load, as to say can not run, it is not responsible for it, that is the responsibility of execution Engine.

# # Execution Engine execution engines

The execution engine, also called the Interpreter (interpreter), is responsible for interpreting the command and committing the operating system execution.

# # Native Interface Local interface

The role of the local interface is to integrate different programming languages for Java, it is the original intention is to merge C/s program, Java was born when the C + + time is rampant, in order to foothold, must have a smart, wise call C + + program, So, in memory, there is an area dedicated to processing code labeled native, it is the practice of native method Stack registered native methods, the execution Engine when the execution of native libraies load. At present, this method is used more and more, unless it is a hardware-related application, such as a Java program to drive a printer, or Java systems to manage production equipment, in enterprise applications has been relatively rare, because the current heterogeneous domain communication is very developed, such as the use of socket communication, You can also use Web Service and so on, do not introduce more.

# # Runtime data area run Datastore

Running the data area is the focus of the entire JVM. All of our written programs are loaded here before they start running, and the Java ecosystem is so prosperous thanks to the good autonomy of the region.

The entire JVM framework is loaded by the loader file, and then the actuator processes the data in memory, and the need to interact with heterogeneous systems can be done through a local interface, see, a complete system was born!

Back to top 3, JVM load class file principle mechanism

All classes in Java need to be loaded by the ClassLoader into the JVM to run. The ClassLoader itself is also a class, and its job is to read the class file from the hard disk into memory. When writing a program, we hardly need to care about the loading of classes, because these are implicitly loaded, unless we have special usages, like reflection, that require explicit loading of the required classes.

Class load mode, there are two types of
1. Implicit loading, when the program runs in the process of generating objects by means of new, implicitly invoking the class loader to load the corresponding class into the JVM,
2. Explicit loading, explicit loading of required classes by means of class.forname (), etc.
The difference between implicit loading and explicit loading: is the two essentially the same?

Java class loading is dynamic, it does not load all classes at once and then run, but to ensure that the program runs the underlying class (such as the base class) fully loaded into the JVM, as for the other classes, it will be loaded when needed. This is of course to save memory overhead.

There are three Java class loaders that correspond to the three kinds of Java: (classes in Java are roughly divided into three types: 1. System Class 2. Extension Class 3. Classes that are custom by programmers)

Bootstrap Loader//Load System class (refers to a built-in class, such as a string, corresponding to the system class in C # and a class in the C + + standard library)
|
--extclassloader//responsible for loading extension classes (that is, inheriting classes and implementing classes)
|
--appclassloader//Load Application Class ( programmer-defined class )

The three loaders do their own work, but how do they coordinate their work? Which class is the class loader to complete? To solve this problem, Java uses the mechanism of the delegation model.

The mechanism of the delegation model works very simply: when the ClassLoader needs to load the class, ask its parent (that is, the previous loader) to load it in its search path, and if not, search for the class in its own search path. This order is actually the top-down search at the loader level, because the loader must ensure that the underlying class is loaded. The reason for this is that there is a security concern: if someone loads a malicious base class into the JVM, the delegate model mechanism searches its parent classloader, which is obviously impossible to find, and naturally does not load the class in.

We can get the class loader through this code:

ClassLoader loader = ClassName.class.getClassLoader (); ClassLoader Parentloader = Loader.getparent ();

Note A very important problem is that Java logically does not exist bootstrapkloader entities! Because it is written in C + +, printing its contents will result in null.

The first is a simple introduction to the ClassLoader, its principle mechanism is very simple, is the following several steps:

1. Loading: Find and import class files;

2. Connection:

(1) Check: Check the correctness of the loaded class file data;

(2) Preparation: Allocate storage space for static variables of class;

(3) parsing: Converting a symbolic reference to a direct reference (this step is optional)

3. Initialize: Initialize static variable, static code block.

Such a procedure begins when the program calls a static member of the class, so the static method main () becomes the entry method for the general program. The constructor of the class will also raise the action.

Java Virtual machine class loading and memory structure

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.