目錄
- 推薦公衆号
- 參考書籍
- 什麼是類加載器
- 類與類加載器
- 類加載模型
-
- 啟動類加載器Bootstrap ClassLoader
- 擴充類加載器Extension ClassLoader
- 應用程式類加載器Application ClassLoader
- 雙親委派模型:
- 破壞雙親委派模型
推薦公衆号
有彩蛋哦!!!(或者公衆号内點選網賺擷取彩蛋)

參考書籍
深入了解Java虛拟機 第二版 周志明著
什麼是類加載器
JVM設計團隊主張把類加載階段”通過一個類的全限定名來擷取此類的二進制位元組流”這個動作放到JVM外部去實作,
以便讓應用程式自己決定如何去擷取所需要的類。實作這個動作的代碼子產品稱為“類加載器”。
類與類加載器
類加載器雖然隻用于實作類的加載動作,但它在java程式中起到的作用卻遠遠不限定于類加載階段。對于任意一個類,
都需要有加在他的類加器器和這個類本身一同确立其在JVM中的唯一性,每一個類加載器,都擁有一個獨立的類名稱空間。
表達的再簡單一點就是:比較兩個類是否相等,隻有在這兩個類是有同一類加載器加載的前提下才有意義,否則即使這兩個類源于統一class檔案,别同一個JVM加載,隻要加載他們的類加載器不一樣,這兩個類就不相等。這裡指的相等,包括代表類的class對象的equals方法,isAssignableFrom方法,isInstance方法的傳回結果;還有instanceof關鍵字的判定情況。
類加載模型
從JVM角度講,隻有兩種不同的類加載器:啟動類加載器Bootstrap ClassLoader,這個類加載器是有c++語言實作的,是JVM自身的一部分;其他類加載器,
這些類加載器都有java語言實作,獨立于JVM外部,并且全部繼承自java.lang.ClassLoader。從開發人員角度講,類加載器還有更細緻的劃分,同時這個層次關系也叫類加載器的雙親委外模型
注意:圖上給出的箭頭隻是說明層次上的定義,并不是絕對的(有的是有的不是)繼承關系;
啟動類加載器Bootstrap ClassLoader
是JVM的一部分,負責加載的是JAVA_HOME/lib下的類庫,或者被-Xbootclasspath參數所指定的路徑中的并且是JVM識别的(僅按照檔案名識别,如rt.jar,名字不符合的類庫即使放在lib目錄中也不會被加載),啟動類加載器無法被JAVA程式直接應用
擴充類加載器Extension ClassLoader
這個類加載由sum.misc.Launcher$ExtClassLoader實作,它負責用于加載JAVA_HOME/lib/ext目錄中的,或者被java.ext.dirs系統變量指定所指定的路徑中的所有類庫,開發者可以直接使用擴充類加載器。Java.ext.dirs系統變量指定的路徑可以通過
System.getProperty("java.ext.dirs")
D:\java\jdk\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext
應用程式類加載器Application ClassLoader
這個類加載器由sun.misc.Launcher$AppClassLoader實作。别名:系統類加載器,如果應用程式中沒有自定義過自己的類加載器,一般情況下這個就是程式中預設的類加載器
public static void main(String[] args) {
System.out.println(ClassLoader.getSystemClassLoader());
}
sun.misc.Launcher$AppClassLoader@18b4aac2
父加載器
public static void main(String[] args) {
System.out.println(ClassLoader.getSystemClassLoader().getParent());
}
sun.misc.Launcher$ExtClassLoader@77468bd9
ExtClassLoader的父加載器
public static void main(String[] args) {
System.out.println(ClassLoader.getSystemClassLoader().getParent().getParent());
}
結果: null
雙親委派模型:
工作過程:如果一個類加載器收到了類加載器的請求,他首先不會自己去嘗試加載這個類,而是把這個請求委派給父類加載器去完成,每一個層次的類加載器都是如此,是以所有的加載請求最終都應該傳送到頂層的啟動類加載器中,隻有當類加載器回報自己無法完成這個加載請求(他的搜尋範圍中沒有找到所需的類)時,子加載器才會嘗試自己去加載。
雙親委派模型的好處:使用雙親委派模型來組織類的加載器之間的關系,能使java類随着他的類加載器一起具備了一種帶有優先級的層次關系。例如類java.lang.Object,它存放在rt.jar中,無論哪一個類加載器要加載這個類,最終都是委派給處于模型最頂端的啟動類加載器進行加載,是以java.lang.Object類在程式的各種類加載器環境中都是同一個類。
雙親委派模型代碼實作 java.langClassLoader loadClass方法
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.
調用自身的findClass方法
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;
}
}
破壞雙親委派模型
書中舉得例子有三種,我舉個最常用得例子
JNDI服務 例如 JDBC
SPI Service Provider Interface 服務提供者
JNDI服務在rt.jar中,應該由啟動類加載器去加載,但是JNDI得接口提供者是各個廠商,在應用程式得ClassPath下,啟動類加載器哪裡會知道這些代碼,這些代碼應該由應用程式類加載器來完成。
為了解決這個問題,引入了線程上下文類加載器(Thread Context ClassLoader)。這個類加載器可以通過java.lang.Thread.setContextClassLoaser()方法設定,如果建立線程未設定則從父線程中繼承一個,如果在應用程式得全局範圍内都沒有設定的話,那這個類加載器預設是應用程式類加載器。那麼JNDI來說就是父加載器調用子加載器來完成加載,就是打通了雙親委派模型的層次結構來逆向使用類加載器,違背了雙親委派模型的一般性原則。
JDBC SPI為例子
通過SPI方式加載JDBC
try {
conn = (Connection)DriverManager.
getConnection(url, user, passwd);
} catch (Exception e) {
System.out.println(e);
}
java.sql.DriverManger
/**
* Load the initial JDBC drivers by checking the System property
* jdbc.properties and then use the {@code ServiceLoader} mechanism
*/
static {
loadInitialDrivers();
println("JDBC DriverManager initialized");
}
private static void loadInitialDrivers() {
先讀取系統屬性 如果沒有設定的話 顯然 擷取出來的是null
String drivers;
try {
drivers = AccessController.doPrivileged(
new PrivilegedAction<String>() {
public String run() {
return System.getProperty("jdbc.drivers");
}
});
} catch (Exception ex) {
drivers = null;
}
// If the driver is packaged as a Service Provider, load it.
// Get all the drivers through the classloader
// exposed as a java.sql.Driver.class service.
// ServiceLoader.load() replaces the sun.misc.Providers()
SPI 注冊
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
注意這個 擷取的ClassLoader
ServiceLoader<Driver> loadedDrivers =
ServiceLoader.load(Driver.class);
Iterator<Driver> driversIterator = loadedDrivers.iterator();
/* Load these drivers, so that they can be instantiated.
* It may be the case that the driver class may not be there
* i.e. there may be a packaged driver with the service class
* as implementation of java.sql.Driver but the actual class
* may be missing. In that case a java.util.ServiceConfigurationError
* will be thrown at runtime by the VM trying to locate
* and load the service.
*
* Adding a try catch block to catch those runtime errors
* if driver not available in classpath but it's
* packaged as service and that service is there in classpath.
*/
try{
while(driversIterator.hasNext()) {
.next中實作注冊
driversIterator.next();
}
} catch(Throwable t) {
// Do nothing
}
return null;
}
});
println("DriverManager.initialize: jdbc.drivers = " + drivers);
if (drivers == null || drivers.equals("")) {
return;
}
String[] driversList = drivers.split(":");
println("number of Drivers:" + driversList.length);
for (String aDriver : driversList) {
try {
println("DriverManager.Initialize: loading " + aDriver);
Class.forName(aDriver, true,
ClassLoader.getSystemClassLoader());
} catch (Exception ex) {
println("DriverManager.Initialize: load failed: " + ex);
}
}
}
/**
* Creates a new service loader for the given service type, using the
* current thread's {@linkplain java.lang.Thread#getContextClassLoader
* context class loader}.
*
* <p> An invocation of this convenience method of the form
*
* <blockquote><pre>
* ServiceLoader.load(<i>service</i>)</pre></blockquote>
*
* is equivalent to
*
* <blockquote><pre>
* ServiceLoader.load(<i>service</i>,
* Thread.currentThread().getContextClassLoader())</pre></blockquote>
*
* @param <S> the class of the service type
*
* @param service
* The interface or abstract class representing the service
*
* @return A new service loader
*/
ServerLoader.java
可以看到是用的線程上下文加載器
public static <S> ServiceLoader<S> load(Class<S> service) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return ServiceLoader.load(service, cl);
}
private S nextService() {
if (!hasNextService())
throw new NoSuchElementException();
String cn = nextName;
nextName = null;
Class<?> c = null;
try {
加載實作類,還沒有初始化;以JDBC為例,此時還沒有完成驅動注冊
c = Class.forName(cn, false, loader);
} catch (ClassNotFoundException x) {
fail(service,
"Provider " + cn + " not found");
}
service就是SPI,以JDBC為例,service就是Java Driver接口;此處判斷c是否為
Driver的實作
if (!service.isAssignableFrom(c)) {
fail(service,
"Provider " + cn + " not a subtype");
}
try {
c是spi的實作,c.newInstance()會觸發類的初始化動作,以JDBC為例,這一操作
完成驅動注冊
S p = service.cast(c.newInstance());
providers.put(cn, p);
return p;
} catch (Throwable x) {
fail(service,
"Provider " + cn + " could not be instantiated",
x);
}
throw new Error();
// This cannot happen
}
為了對比 寫一下通過系統屬性注冊驅動
try {
System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver");
conn = (Connection)DriverManager.
getConnection(url, user, passwd);
} catch (Exception e) {
System.out.println(e);
}
那下面就清楚,設定玩系統屬性
static {
loadInitialDrivers();
println("JDBC DriverManager initialized");
}
private static void loadInitialDrivers() {
先讀取系統屬性 如果沒有設定的話 顯然 擷取出來的是null
String drivers;
try {
drivers = AccessController.doPrivileged(
new PrivilegedAction<String>() {
public String run() {
return System.getProperty("jdbc.drivers");
}
});
} catch (Exception ex) {
drivers = null;
}
// If the driver is packaged as a Service Provider, load it.
// Get all the drivers through the classloader
// exposed as a java.sql.Driver.class service.
// ServiceLoader.load() replaces the sun.misc.Providers()
SPI 注冊
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
注意這個 擷取的ClassLoader
ServiceLoader<Driver> loadedDrivers =
ServiceLoader.load(Driver.class);
Iterator<Driver> driversIterator = loadedDrivers.iterator();
/* Load these drivers, so that they can be instantiated.
* It may be the case that the driver class may not be there
* i.e. there may be a packaged driver with the service class
* as implementation of java.sql.Driver but the actual class
* may be missing. In that case a java.util.ServiceConfigurationError
* will be thrown at runtime by the VM trying to locate
* and load the service.
*
* Adding a try catch block to catch those runtime errors
* if driver not available in classpath but it's
* packaged as service and that service is there in classpath.
*/
try{
while(driversIterator.hasNext()) {
.next中實作注冊
driversIterator.next();
}
} catch(Throwable t) {
// Do nothing
}
return null;
}
});
println("DriverManager.initialize: jdbc.drivers = " + drivers);
if (drivers == null || drivers.equals("")) {
return;
}
String[] driversList = drivers.split(":");
println("number of Drivers:" + driversList.length);
for (String aDriver : driversList) {
try {
println("DriverManager.Initialize: loading " + aDriver);
Class.forName(aDriver, true,
ClassLoader.getSystemClassLoader());
} catch (Exception ex) {
println("DriverManager.Initialize: load failed: " + ex);
}
}
}