当前位置:网站首页>Jvm: thread context classloader

Jvm: thread context classloader

2022-06-12 01:09:00 amadeus_ liu2

One 、 When the context class loader is not actively set , The thread context class loader is the application class loader (AppClassLoader)

1. introduce MySQL package

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>

2. test ThreadContextClassLoader

package cn.edu.tju;

import java.sql.Driver;
import java.util.Iterator;
import java.util.ServiceLoader;

public class ThreadContextClassLoaderTest {
    public static void main(String[] args) {
        ServiceLoader<Driver> serviceLoader=ServiceLoader.load(Driver.class);
        Iterator<Driver> iterator = serviceLoader.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next().getClass());
        }
    }
}

3. Operation output :
 Insert picture description here
4. Result analysis : Because there are no settings ThreadContexClassLoader, So the main thread ThreadContextClassLoader by AppClassLoader, It can be loaded from the application's classpath MySQL Of the two Driver class .

5. Modify main class :

package cn.edu.tju;

import java.sql.Driver;
import java.util.Iterator;
import java.util.ServiceLoader;

public class ThreadContextClassLoaderTest {
    public static void main(String[] args) {
        Thread.currentThread().setContextClassLoader(SpiTest.class.getClassLoader().getParent());
        
        ServiceLoader<Driver> serviceLoader=ServiceLoader.load(Driver.class);
        Iterator<Driver> iterator = serviceLoader.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next().getClass());
        }
    }
}

Change the context class loader of the thread to AppClassLoader Of parent namely ExtClassLoader, Will not be able to load... Under the classpath MySQL Of Driver class , therefore , The program runs without output

原网站

版权声明
本文为[amadeus_ liu2]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206120104213399.html