• JVM 类加过程及类加载器简介


    类加载过程

    我们知道 JVM 的类加载过程分为加载、连接、初始化三个阶段。
    加载阶段主要做了三件事:

    1. 根据的全限定名找到 class 文件字节流
    2. 将二进制字节流转换为 JVM 内存中的元数据结构
    3. 生成这个类的 Class 对象

    连接阶段分为验证、准备、解析三个过程。

    • 验证过程主要进行文件格式、元数据、字节码等的一系列验证确保文件合法且安全。
    • 准备过程主要对类变量赋默认值,一般类变量的默认值就是类型的零值,常量除外。
    • 解析过程主要完成符号引用到直接引用的转换。

    初始化阶段主要进行静态代码块的执行。其中类变量的赋初始值操作会被合并到静态代码快中,多个静态代码块会被按照源码中的编写顺序进行合并。

    类加载器

    说到类加载器一定绕不开 Java 类加载器的双亲委派模型。我们可以从 ClassLoader 的源码中找到双亲委派的由来。

        /**
         * Loads the class with the specified <a href="#name">binary name</a>.
         * This method searches for classes in the same manner as the {@link
         * #loadClass(String, boolean)} method.  It is invoked by the Java virtual
         * machine to resolve class references.  Invoking this method is equivalent
         * to invoking {@link #loadClass(String, boolean) <tt>loadClass(name,
         * false)</tt>}.
         *
         * @param  name
         *         The <a href="#name">binary name</a> of the class
         *
         * @return  The resulting <tt>Class</tt> object
         *
         * @throws  ClassNotFoundException
         *          If the class was not found
         */
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            return loadClass(name, false);
        }
    
    protected Class<?> loadClass(String name, boolean resolve)
            throws ClassNotFoundException
        {
            synchronized (getClassLoadingLock(name)) {
                // First, check if the class has already been loaded
                Class<?> c = findLoadedClass(name);
                if (c == null) {
                    long t0 = System.nanoTime();
                    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.
                        long t1 = System.nanoTime();
                        c = findClass(name);
    
                        // this is the defining class loader; record the stats
                        sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                        sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                        sun.misc.PerfCounter.getFindClasses().increment();
                    }
                }
                if (resolve) {
                    resolveClass(c);
                }
                return c;
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    从 loadClass 方法的逻辑我们可以看到一般系统中默认的类加载器(AppClassLoader)进行类加载的过程如下:
    类加载过程图
    上图这种向上委派查找,向下委派加载的过程就叫做双亲委派模型。

    在无自定义类加载器的情况下,classpath 下的类一般都是由 AppClassLoader 类加载器进行加载的。AppClassLoader 的 parent 是 ExtClassLoader,ExtClassLoader 的 parent 是 null,也就是 BootstrapClassLoader。这种关系我们可以通过 sun.misc.Launcher 的构造来找到:

        public Launcher() {
            Launcher.ExtClassLoader var1;
            try {
                var1 = Launcher.ExtClassLoader.getExtClassLoader();
            } catch (IOException var10) {
                throw new InternalError("Could not create extension class loader", var10);
            }
    
            try {
                this.loader = Launcher.AppClassLoader.getAppClassLoader(var1);
            } catch (IOException var9) {
                throw new InternalError("Could not create application class loader", var9);
            }
    
            Thread.currentThread().setContextClassLoader(this.loader);
            String var2 = System.getProperty("java.security.manager");
            if (var2 != null) {
                SecurityManager var3 = null;
                if (!"".equals(var2) && !"default".equals(var2)) {
                    try {
                        var3 = (SecurityManager)this.loader.loadClass(var2).newInstance();
                    } catch (IllegalAccessException var5) {
                    } catch (InstantiationException var6) {
                    } catch (ClassNotFoundException var7) {
                    } catch (ClassCastException var8) {
                    }
                } else {
                    var3 = new SecurityManager();
                }
    
                if (var3 == null) {
                    throw new InternalError("Could not create SecurityManager: " + var2);
                }
    
                System.setSecurityManager(var3);
            }
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    sun.misc.Launcher$ExtClassLoader 中的工具方法 getExtClassLoader 逻辑如下:

        public static Launcher.ExtClassLoader getExtClassLoader() throws IOException {
                final File[] var0 = getExtDirs();
    
                try {
                    return (Launcher.ExtClassLoader)AccessController.doPrivileged(new PrivilegedExceptionAction<Launcher.ExtClassLoader>() {
                        public Launcher.ExtClassLoader run() throws IOException {
                            int var1 = var0.length;
    
                            for(int var2 = 0; var2 < var1; ++var2) {
                                MetaIndex.registerDirectory(var0[var2]);
                            }
    
                            return new Launcher.ExtClassLoader(var0);
                        }
                    });
                } catch (PrivilegedActionException var2) {
                    throw (IOException)var2.getException();
                }
            }
    
            public ExtClassLoader(File[] var1) throws IOException {
                super(getExtURLs(var1), (ClassLoader)null, Launcher.factory);
                SharedSecrets.getJavaNetAccess().getURLClassPath(this).initLookupCache(this);
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    这里补充一下 ClassLoader 模板类的构造方法,一共有三个,分为两种,一种指定 parent,一种不指定,默认 parent 为 AppClassLoader.代码如下:

        private ClassLoader(Void unused, ClassLoader parent) {
            this.parent = parent;
            if (ParallelLoaders.isRegistered(this.getClass())) {
                parallelLockMap = new ConcurrentHashMap<>();
                package2certs = new ConcurrentHashMap<>();
                domains =
                    Collections.synchronizedSet(new HashSet<ProtectionDomain>());
                assertionLock = new Object();
            } else {
                // no finer-grained lock; lock on the classloader instance
                parallelLockMap = null;
                package2certs = new Hashtable<>();
                domains = new HashSet<>();
                assertionLock = this;
            }
        }
        
        ... ...
        
        protected ClassLoader(ClassLoader parent) {
            this(checkCreateClassLoader(), parent);
        }
        
        ... ...
    
        protected ClassLoader() {
            this(checkCreateClassLoader(), getSystemClassLoader());
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    有上面的代码逻辑我们可以推导得到 ClassLoader 的层次结构如下:
    ClassLoader 层次图

  • 相关阅读:
    微信小程序 电影院售票选座票务系统5w7l6
    一张草图直接生成视频游戏,谷歌推出生成交互大模型
    Vue3表单组件el-form校验规则rules属性
    Arduino开发实例-DIY空气粉尘密度检测仪
    免费文档翻译软件电脑版软件
    [附源码]java毕业设计基于新高考模式下的排课系统
    【入门-03】时钟系统
    Rainbond 携手 TOPIAM 打造企业级云原生身份管控新体验
    【Hack The Box】windows练习-- Bankrobber
    C++(17):make_from_tuple
  • 原文地址:https://blog.csdn.net/phaeton_lai/article/details/125470824