In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to deeply understand Java virtual machine JVM class loading initialization, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.
1. Generally speaking, the function of Classloader is to load and load the compiled class into the machine memory, which provides a prerequisite for the future execution of the program.
two。 The thinking caused by a program:
Mr. Ye in the wind gave us a program in his video, which claimed to be a mistake made by all Java programmers in the world.
The weird code is as follows:
Java code
Package test01; class Singleton {public static Singleton singleton = new Singleton (); public static int a; public static int b = 0; private Singleton () {super (); public static Singleton GetInstence () {return singleton }} public class MyTest {/ * * @ param args * / public static void main (String [] args) {Singleton mysingleton = Singleton.GetInstence (); System.out.println (mysingleton.a); System.out.println (mysingleton.b);}}
The general unthinkable conclusion is that axiom 1 is not exactly what it is. The reason given is that both an and b are static variables and have been added to both an and b when the constructor is called. The answer is all 1. But after running it, the answer is axiom 1, no. 0.
Let's change the code a little bit.
Java code
Public static Singleton singleton = new Singleton (); public static int a; public static int b = 0
Replace part of the code with
Java code
Public static int a; public static int b = 0; public static Singleton singleton = new Singleton ()
The effect is what was expected just now.
Why, these three sentences are nothing more than the declaration and initialization of static variables, does the change of values have anything to do with the order of declaration? isn't Java object-oriented? Like structured language, the order has something to do with it. This is directly related to the principle of loading classes in the Java virtual machine JVM.
1. How classes work in JVM
To work for yourself with a Java class, you must go through the following processes
1): class load load: load the class into memory from the bytecode binary file-.class file, thus achieving a migration of the class from the hard disk to memory, and all programs must be loaded into memory to work. Put the class in memory into the method area of the runtime data area, and then create a java.lang.Class object in the heap area to encapsulate the data structure of the method area. At this time, it shows that everything is an object, and there must be an object for everything to do. When it comes to the * layer, is it a chicken laying eggs or an egg laying chicken? The end product of class loading is a java.lang.Class object in the heap.
2): connection: the connection is divided into the following small steps
Verification: for the sake of security, verify whether the bytecode in memory conforms to the JVM specification, whether the class structure specification, semantic check, and bytecode operation are legal, which is to prevent users from creating an illegal XX.class file to work, or because of JVM version conflicts, such as class compiled under JDK6 (including annotated classes) Cannot be run under the JVM of JDK1.4.
Prepare: allocate memory space for static variables of the class and initialize default values. (the object hasn't been generated yet, so there are no instance variables at this time.)
Parsing: change the symbolic reference of a class to a direct reference (reserved)
3): initialization of the class: assign the static variable of the class to the correct initial value, which is the initial value defined by the developer, not the default value.
two。 Active and passive use of classes
The following is regarded as active use of a class, other cases are regarded as passive use!
1): new an instance object of a class most commonly used by beginners (declaration is not called active use)
2): read and assign the static variables of the class.
3): call the static method of the class directly.
4): reflection calls the method of a class.
5): when initializing a subclass of a class, the parent class is also called actively by the program (if the static variable of the calling subclass is inherited from the parent class and is not overwritten, then it is equivalent to using only the things of the parent class. It has nothing to do with the subclass, so the subclass does not need class initialization at this time).
6): run a class directly to the entry of the main function.
All JVM implementations (different vendors have different implementations, some people say that the implementation of IBM is better than that of Sun.) Classes and interfaces are initialized only when they are actively called.
1. How the class is loaded
1): load directly in the locally compiled class
2): network loading: java.net.URLClassLoader can load classes specified by url
3): load classes from jar, zip and other compressed files, automatically parse jar files and find class files to load util classes
4): dynamically compile from a java source code file to a class file
two。 Class loader
Default loader included with JVM
1): root class loader: bootstrap, written by C++, all Java programs are not available.
2): extension class loader: written by Java.
3): system class, application class loader: written by Java.
User-defined class loader: a subclass of java.lang.ClassLoader, users can customize how the class is loaded. Each class contains a reference to load its ClassLoader-- getClass (). GetClassLoader (). If null is returned, it proves that the ClassLoader that loaded him is the root loader bootstrap.
The code is as follows
The pointer in this is the pointer of C++.
1. Review that weird code.
Start from the entrance.
Singleton mysingleton = Singleton.GetInstence ()
An instance of Singleton is required based on the static method of the inner class.
At this point, it is time to actively call the Singleton class.
Then memory starts to load the Singleton class
1): allocate space to all static variables of Singleton, assigning default values, so at this time, singleton=null, astat0, bicon0. Note that 0 of b is the default value, not the 0 value that we manually assigned to it.
2): then assign a value to the static variable, and the assignment at this time is the value we initialized manually in the program. At this point, singleton = new Singleton (); calls the constructor. In the constructor, astat1, bread1. And then proceed sequentially.
3):
Public static int a; public static int b = 0
A has no assignment and remains as it is. B is assigned, b's original 1 value is overwritten, b is 0. So that's how it turned out. The static block static blocks in the class are also executed sequentially from top to bottom.
two。 Static variables of compile-time constant and non-compile-time constant
The code is as follows
Java code
Package test01; class FinalStatic {public static final int A = 4 + 4; static {System.out.println ("if executed, prove that the class initialized …") ;} public class MyTest03 {/ * * @ param args * / public static void main (String [] args) {System.out.println (FinalStatic.A);}}
The result is that only 8 is printed, proving that the class is not initialized. Decompilation of the source code found that the contents of class are
Public static final int A = 8
In other words, the compiler is smart enough to figure out that 4-4 is 8, which is a fixed number. There is no unknown factor in it.
Change the code a little bit
Public static final int A = 4 + new Random () .nextInt (10)
At this point, the static block is executed, proving that the class is initialized. In cases where static final variables are uncertain at compile time. If the client accesses the static variable of the class at this time, the class will be initialized, so try to have no variables in the static final variable 1, otherwise the performance will degrade.
1. Analysis of ClassLoader
Loading a class by ClassLoader's loadClass method is not an active call and does not cause the class to initialize. The following code block
Java code
ClassLoader classLoader = ClassLoader.getSystemClassLoader (); Class clazz = classLoader.loadClass ("test01.ClassDemo")
The classloader is not asked to initialize the test01.ClassDemo because this is not an active call to this class.
The relationship of ClassLoader:
Root loader-- extended classloader-- Application classloader-- user-defined classloader
The process of loading a class starts from the root loader, which cannot be loaded by the root loader, which is loaded by the extended class loader, and then can not be loaded by the application loader. If the application loader cannot be loaded, it will be loaded by a custom loader (which must be inherited from java.lang. ClassLoader) load, if the custom loader does not load. And there is no more special class loader below, ClassNotFoundException will be thrown. On the surface, the exception is that the class can not be found, but in fact, it is the failure of class loading, let alone create the Class object of this class.
If a class can be loaded successfully at a certain layer of class loader, then the loader at that layer is called definition class loader. Then the Class reference generated at this layer of class is returned to the next layer loader called the initial class loader. Because a successful load returns a Class reference to its service object-- that is, the class loader that invokes it. For security reasons, the parent delegate loading mechanism.
The original code of the ClassLoader load class is as follows
Java code
Protected synchronized Class loadClass (String name, boolean resolve) throws ClassNotFoundException {/ / First, check if the class has already been loaded Class c = findLoadedClass (name); if (c = = null) {try {if (parent! = null) {c = parent.loadClass (name, false);} else {c = findBootstrapClassOrNull (name) } catch (ClassNotFoundException e) {/ / ClassNotFoundException thrown if class not found / / from the non-null parent class loader} if (c = = null) {/ / If still not found, then invoke findClass in order / / to find the class. C = findClass (name);}} if (resolve) {resolveClass (c);} return c;}
The initialization system ClassLoader code is as follows
Java code
Private static synchronized void initSystemClassLoader () {if (! sclSet) {if (scl! = null) throw new IllegalStateException ("recursive invocation"); sun.misc.Launcher l = sun.misc.Launcher.getLauncher (); if (l! = null) {Throwable oops = null; scl = l.getClassLoader () Try {PrivilegedExceptionAction a; a = new SystemClassLoaderAction (scl); scl = (ClassLoader) AccessController.doPrivileged (a);} catch (PrivilegedActionException pae) {oops = pae.getCause (); if (oops instanceof InvocationTargetException) {oops = oops.getCause () }} if (oops! = null) {if (oops instanceof Error) {throw (Error) oops;} else {/ / wrap the exception throw new Error (oops) } sclSet = true;}}
It calls a lot of native methods, that is, the code that calls the underlying C++ through JNI.
When a class is loaded, connected, and initialized, its life cycle begins, and when the Class object representing the class is no longer referenced, that is, it is untouchable, the life cycle of the Class object ends. Then the data in the method area of this class will also be unloaded, thus ending the life cycle of the class. The life cycle of a class depends on the life cycle of its Class object. Classes loaded by the default loaders included with the Java virtual machine (root loader, extension loader, system loader) are never unloaded throughout the JVM lifecycle. So the Class objects of these classes (I call them instance template objects) can always be touched! The classes loaded by the user-defined class loader will be unloaded!
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.