Java underlying Learning

Source: Internet
Author: User

Well, the interview is coming soon. The bottom layer of Java must be understood. I found the underlying Java article on the Internet and made a mark. The underlying layer of Java is mainly the loading, connection, and initialization of classes.

This article mainly consists of four aspects:

(1) Java underlying Overview

(2) differences between new and newinstance () Methods

(3) Explore Java's loading mechanism in Depth

(4) Complete JAVA Program Execution Process for Java XXX. Class

The four parts are from the Internet. After reading the four parts, you should have some knowledge of the underlying Java layer.

The following text is from crazy Java handout:

1. class loading, connection, and initialization

When the system takes the initiative to use a class, if the class has not been loaded into the memory, the system will load, connect, initialize three steps.
1. Load the class to read the class file of the class into the memory, and create a java. Lang. Class Object for it.
Class File Source:
(1) load the class file locally
(2) load from the jar package (system API)
(3) load from the network
2. Class connection:
The connection phase is used to merge binary data of the class into the JRE.
3. class initialization
Class initialization time:
(1) create a class instance: new operator, reflection to create an instance, and deserialization;
(2) Call static methods of a class;
(3) Access static attributes of a class (except final attributes ).

2. Differences between the new operator and the newinstance () method

Http://lvqingboy-163-com.iteye.com/blog/657599

When a class is initialized and an instance is generated, what are the main differences between the newinstance () method and the New Keyword, except the method and the keyword? The difference between them is that the method for creating objects is different. The former uses the class loading mechanism, and the latter creates a new class. So why are there two ways to create objects? This mainly takes into account software design ideas such as software scalability, scalability and reusability.

In Java, the newinstance () method is often used to create objects in the factory mode. Therefore, you can find specific answers to the question of why the factory mode is used. For example:
Class C = Class. forname ("Example ");
Factory = (exampleinterface) C. newinstance ();

Here, exampleinterface is the example interface, which can be written as follows:
String classname = "example ";
Class C = Class. forname (classname );
Factory = (exampleinterface) C. newinstance ();

It can be further written as follows:
String classname = readfromxmlconfig; // obtain the string from the xml configuration file
Class C = Class. forname (classname );
Factory = (exampleinterface) C. newinstance ();

The above Code does not have the example class name. Its advantage is that, no matter how the example class changes, the above Code remains unchanged, and you can even replace example's sibling classes example2, example3, example4 ......, As long as they inherit exampleinterface.

From the JVM perspective, when we use the keyword new to create a class, this class can not be loaded. However, when using the newinstance () method, you must ensure that: 1. This class has been loaded; 2. This class has been connected. The above two steps are completed by the static class method forname (). This static method calls the start class loader, that is, the loader that loads the Java API.

It can be seen that newinstance () is actually to break down the new method into two steps, that is, first call the class loading method to load a class and then instantiate it. The benefits of this step-by-step operation are obvious. We can get better flexibility when calling the class Static Loading Method forname, and provide a means of downcoupling.

Finally, we use the simplest description to distinguish the New Keyword from the newinstance () method:
Newinstance: weak type. Low efficiency. Only construction without parameters can be called.
New: strong type. Relatively efficient. Can call any public constructor.

My understanding:

In fact, the newinstance () method is to explicitly load:

The forname (string s) method of the class loads the custom class testclass and initializes the instance through the newinstance () method.

The new operator is implicitly loaded: when JRE executes the New Keyword, it loads the corresponding instance class into the memory.

3. Discuss Java classloader mechanism in Depth

Http://www.blogjava.net/William/archive/2006/08/25/65804.html

Java is a dynamic interpreted programming language. When a specified program runs, the Java Virtual Machine will compile and generate the program. class files are loaded into the memory according to requirements and certain rules, and organized into a complete Java application. The Java language compiles each separate class and interface implements into a separate. Class file. These files are dynamic loaded units for the Java Runtime Environment. It is precisely because of this feature of Java that we can compile only the units to be modified without re-compiling other code, and compile the. Class
The file is placed in the Java path. When the Java Virtual Machine is re-activated next time, the logic-based Java application will load the new modified. class file, and its own functions have also been updated, which is the dynamic nature of Java.

The following is a simple example to give you a basic understanding of Java's dynamic loading:

class TestClassA{         publicvoid method(){                   System.out.println("LoadingClassA");         }}public class ClassLoaderTest {         publicstatic void main(String args[]){                   TestClassAtestClassA = new TestClassA();                   testClassA.method();         }} 

After compilation, enter the command: Java-verbose: Class classloadertest to execute the file. (Java-verbose: Class: Check the loading status of the Class)

Output structure (1)

Figure (1)

From the running results, we can see that JRE (javaruntime environment) First loads the classloadertest file and then loads the testclassa file, thus implementing dynamic loading.

1.Pre-load and load as needed

To optimize the system and improve the program execution speed, the Java Runtime Environment uses pre-loading (pre-loading) all the methods are loaded into the memory, because these units are often used during the Java program running process, mainly including the RT of JRE. all. class file.

After the java. EXE virtual machine starts running, it will find the JRE environment installed on the machine, and then hand over the control to the JRE. The JRE class loader will RT under the lib directory. the jar basic category file library is loaded into the memory. These files are required for Java program execution. Therefore, the system loads these files at the beginning to avoid multiple I/O operations in the future, this improves program execution efficiency.

Figure (2) We can see that multiple basic classes are loaded, java. Lang. Object, java. Io. serializable, and so on.

Figure (2)

Compared with pre-loading, we need to use the load-on-demand method when we need to use the class defined by ourselves in the program ), it is re-loaded when the Java program needs to be used to reduce memory consumption, because the original design of the Java language is oriented to the embedded field.

It is worth noting that when does JRE load classes into the internal environment as needed?

When defining a class instance, such as testclassa, the value of testclassa is null, that is, it has not been initialized and has not called the testclassa constructor, JRE loads testclassa only after testclassa = new testclassa () is executed.

2.Implicit and explicit Loading

Implicit loading: use the new operator;

Display loading: Use the forname () method: forname (string s) method of the class to load the custom class testclass, and initialize the instance using the newinstance () method.

Java load methods include implicit loading (implicit) and explicit loading (explicit). The above example uses the implicit loading method. Implicit loading means that we use the new keyword in the program to define an instance variable. when JRE executes the New Keyword, it loads the corresponding instance class into the memory. Implicit loading is very common and widely used. The JRE system automatically loads data in the background, reducing the workload and increasing the system security and program readability.

Compared with implicit loading, display loading is not frequently used. The so-called display loading means that some programmers write their own programs to load the required classes into the memory. Let's look at a program:

class TestClass{         publicvoid method(){                   System.out.println("TestClass-method");         }} public class CLTest {         publicstatic void main(String args[]) {                  try{                            Classc = Class.forName("TestClass");                            TestClassobject = (TestClass)c.newInstance();                            object.method();                   }catch(Exceptione){                            e.printStackTrace();                   }         }} 

We load the custom class testclass through the forname (string s) method of the class, and initialize the instance through the newinstance () method. In fact, the class still has many functions. I will not elaborate on them here. If you are interested, refer to the JDK documentation.

The forname () method of class has another form: Class forname (string S, Boolean flag, classloader). S indicates the name of the class to be loaded, flag indicates whether the static zone is initialized when the function is called to load the class, and classloader indicates the loader required to load the class.

Forname (string S) is implemented by classloader by default. getcallerclassloader () calls the class loader, but this method is private and cannot be called. If we want to use class forname (string S, Boolean flag, classloader) to load the class, you must specify the class loader, which can be implemented in the following way:

Test test = new test (); // The test class is a custom test class;

Classloader Cl = test. getclass (). getclassloader ();

// Obtain the class loader of test;

Class C = Class. forname ("testclass", true, Cl );

To load a class, you must have a loader. Here we get the loader CL for loading the test class and use it as the class loader for loading the testclass.

3. Custom class loading mechanism

Previously, we used to call the class loader of the system to implement loading. In fact, we can define the Class Loader ourselves. Java provides the java.net. urlclassloader class. The following is an example:

try{                            URLurl = new URL("file:/d:/test/lib/");                            URLClassLoaderurlCL = new URLClassLoader(new URL[]{url});                            Classc = urlCL.loadClass("TestClassA");                            TestClassAobject = (TestClassA)c.newInstance();                            object.method();                   }catch(Exceptione){                            e.printStackTrace();                   }

We use a custom class loader to load the testclassa class and call the method () method. Analyze this program: first, define the URL to specify where the Class Loader loads the class. The URL can point to any location on the Internet, you can also point to the file system (including jar files) in our computer ). In the above example, we will look for classes from file:/D:/test/lib/. Then we will define urlclassloader to load the required classes, and then we will use this instance.

4. Class Loader Class System

After so much discussion, let's take a closer look at the working principle of the Java Class Loader:

When Java *** is executed ***. class, java.exe will help us find the JRE, and then find the JVM located inside the JRE. DLL, which is the real Java Virtual Machine. Finally, load the dynamic library and activate the Java Virtual Machine. After the virtual machine is activated, initialization will be performed first, such as reading system parameters. Once the initialization is complete, the bootstrap loader, the first class loader, is generated. bootstrap loader is written by C ++. In the initial work of this bootstrap loader, in addition to some basic initialization actions, the most important thing is to load
Extclassloader in launcher. Java, and set its parent to null, which indicates that its parent loader is bootstraploader. Then bootstrap loader needs to load the appclassloader in launcher. Java and set its parent to the previously generated extclassloader object. Both loaders exist in the form of static classes. Please note that launcher $ extclassloader. Class and launcher $ appclassloader. Class
It is loaded by bootstrap loader, so parent has nothing to do with which class loader to load.

The following figure shows the relationship between the three elements:

Parent class

Parent class

Load

Load

Bootstraploader

Parent

Appclassloader

Parent

Extclassloader

These three loaders constitute our Java class loading system. They look for the classes required by the program from the following paths:

Bootstraploader: Sun. boot. Class. Path

Extclassloader: Java. Ext. dirs

Appclassloader: Java. Class. Path

The three system parameters can be obtained through the system. getproperty () function. You can view the specific path by programming.

5. Summary

Understanding the class loading mechanism of Java plays an important role in skillfully and flexibly using the Java language and improving the running efficiency of programs, in this way, the program quality can be improved as a whole.

4. go deep into the Java underlying layer

Http://bigwhite.blogbus.com/logs/579744.html

On a friend's shelf, I found Wang Sen's book "Java deep Adventure". I read the preface of the book to understand the story about the underlying Java technology. I browsed it with curiosity. I could not talk about too much gains, but I also noted down some points that I think are helpful.

Java xxx

We typed in the command line: what will happen after "Java XXX?

The process is as follows:

 

1. Find JRE;

 

2. Find JVM. dll;

 

3. Start JVM and initialize it;

 

4. Generate bootstrap loader;

 

5. Load extclassloader; (ext-extended)

 

6. Load appclassloader;

 

7. Load the xxx class.

 

The book mentions that bootstrap loader, extclassloader, and appclassloader constitute the "Class Loader inheritance system-Class Loader hierarchy" of Java. bootstraploader is compiled by C ++, the other two are written in Java. The reason for becoming an "Inheritance System" is that these three loaders are related. Bootstrap loader is responsible for loading extclassloader. The latter extclassloader sets its parent as bootstrap loader. Appclassloader is special. Although it is loaded by bootstrap, its parent is set to extclassloader. The reason is to implement the "delegated model ". In brief, the "delegated model" means that when the class loader needs to load classes, it will first request its parent to use its search path for help loading. If its parent cannot be found, to use your own search path for loading. As mentioned above, when extclassloader wants to load the appclassloader class, it first requests its parent
"Bootstrap loader" helps. After bootstrap loader loads appclassloader, the parent of appclassloader is set to extclassloader rather than bootstrap loader because this is the extclassloader request.

Class loading process

Class loading follows the principle: "The Class Loader loads classes from top to bottom according to the class inheritance system ". For example, "If C inherits B and implements interface I while B inherits from a", when the class loader loads C, the loading order will be a-> B-> I-> C. (Note: The interface will be compiled as independent by the Java compiler like the class. class file)

In fact, I have not paid too much attention to the underlying things. If I need to know the underlying things in any project, I will study well.

 

By the way, what is the DLL?

Http://baike.baidu.com/view/887.htm

The dynamic link library (DLL) is short for dynamiclink library. dll is a library that contains code and data that can be used by multiple programs at the same time. dll is not an executable file. Dynamic links provide a way for a process to call a function that does not belong to its executable code. The executable code of the function is located in
DLL, which contains one or more functions that have been compiled, linked, and stored separately from the processes that use them. DLL also helps to share data and resources. Multiple applications can simultaneously access the content of a single DLL copy in the memory. DLL is a library that contains code and data that can be used by multiple programs at the same time.


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.