双亲委派模型加载过程(以类A为例):
1.从最底层类加载器开始,最底层类加载器判断类A是否被自己加载过,加载过直接返回,否则转2;
2.将类A加载权交给父类加载器,父类加载器判断类A是否被自己加载过,加载过返回,否则继续将类A加载权交给父类,一直到启动类加载器(BootStrapClassLoader)为止;
3.若启动类加载器若加载过返回,否则从jre\lib路径加载此类,若类A在此路径中,加载成功返回,若类A不在此路径中,重新将加载权交给子类;
4.子类对类A进行加载,加载成功返回,否则继续将加载权交给子类,一直到最底层类加载器为止,若最底层类加载器加载失败,则代表类A最终加载失败。
注:类加载器中的子类父类关系是通过组合实现的,而非继承。如果没有自定义类加载器,最底层类加载器为应用程序类加载器(sun.misc.Launcher$AppClassLoader)。
自定义类加载器:
1.当重写findClass()方法时,遵循双亲委派模型;
2.当重写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.
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;
}
}
protected Class<?> findClass(String name) throws ClassNotFoundException {
throw new ClassNotFoundException(name);
}
类加载机制作用
进行java类的热替换,即在不停止正在运行的系统的情况下进行类(对象)的升级替换。
- 同一个类加载器对同一个类最多只能defineClass()一次,否则出错(java.lang.LinkageError:attempted duplicate class definition)
- 在loadClass()某个类时,会对此类的父类、实现的接口均进行loadClass(),且loadClass()属于同一个类加载器
下面演示一个热替换的例子:
此例子共4个文件:Hello.java对应的Hello.class是被热替换的类,IHello是Hello类的接口,MyClassLoader是自定义的类,Test是程序入口。
package hotswap;
public interface IHello {
void sayHello();
}
package hotswap;
public class Hello implements IHello{
public void sayHello() {
System.out.println("hello version-1");
}
}
下面是自定义类加载器,重写了ClassLoader的loadClass方法,涉及到的其他方法还有findLoadedClass,getSystemClassLoader,defineClass,resolveClass
import java.io.File;
import java.io.FileInputStream;
public class MyClassLoader extends ClassLoader {
private String loadPath;
private String[] fileNames;
public MyClassLoader(String loadPath, String[] fileNames) {
this.loadPath = loadPath;
this.fileNames = fileNames;
}
private boolean isInSelfLoadRange(String name) {
for (String fileName : fileNames) {
if (fileName.equals(name))
return true;
}
return false;
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
Class<?> cls= findLoadedClass(name);
try {
if (cls == null) {
if (isInSelfLoadRange(name)) {
FileInputStream in = new FileInputStream(loadPath
+ name.replace('.', File.separatorChar) + ".class");
int len = in.available();
byte[] b = new byte[len];
in.read(b);
in.close();
cls = defineClass(name, b, 0, len);
} else {
cls = getSystemClassLoader().loadClass(name);
}
}
} catch (Exception e) {
throw new ClassNotFoundException();
}
resolveClass(cls);
return cls;
}
}
import hotswap.IHello;
import java.util.Timer;
import java.util.TimerTask;
public class Test {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
MyClassLoader loader = new MyClassLoader(System
.getProperty("user.dir") +"\\bin\\",
new String[] { "hotswap.Hello" });
Class<?> c = loader.loadClass("hotswap.Hello");
IHello obj = (IHello) c.newInstance();
obj.sayHello();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 3000, 5000);
}
}
运行程序,刚开始输出hello version-1,然后在程序继续运行的情况下,将Hello.java中的输出语句依次变为hello version-2、hello version-3,并编译为class文件覆盖掉原来的class文件,程序运行结果如下:
hello version-1
hello version-1
hello version-2
hello version-3
hello version-3
hello version-3
破坏双亲委派模型
现在我们来考虑一种情况,当我们在java中连接数据库时,我们需要在高层类DriverManager(位于jre\lib目录下)的getConnection方法中调用具体的位于底层(在工作空间中)的数据库驱动类,这时如果你是DriverManager类的设计者,你会怎么办?
我们有以下几种备选方法:
- 直接加载,由于加载DriverManager的类加载器BootStrapClassLoader无法找到此类的位置,无法对其加载,行不通,由此可知需要破坏双亲委派机制;
- 委托给系统类加载器(ClassLoader.getSystemClassLoader()),由于系统类加载器在不同的系统中指向的类加载器不同,行不通;
- 委托给调用DriverManager.getConnection()方法的类,设其为类A,由于调用DriverManager.getConnection()方法的类A不确定,故加载类A的类加载器(Reflection.getCallerClass().getClassLoader())不确定,行不通;
那么应该怎么办呢?
通过线程上下文类加载器来进行加载。
连接数据库:
String url = "jdbc:mysql://localhost:3306/cm-storylocker?characterEncoding=UTF-8";
// 通过java库获取数据库连接
Connection conn = java.sql.DriverManager.getConnection(url, "root", "root@555");
DriverManager的相关源码(其中loadInitialDrivers()中有利用线程上下文类加载器来加载类的逻辑):
private final static CopyOnWriteArrayList<DriverInfo> registeredDrivers = new CopyOnWriteArrayList<>();
static {
loadInitialDrivers();
println("JDBC DriverManager initialized");
}
private static void loadInitialDrivers() {
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()
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
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()) {
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);
}
}
}
public static Connection getConnection(String url,
String user, String password) throws SQLException {
java.util.Properties info = new java.util.Properties();
if (user != null) {
info.put("user", user);
}
if (password != null) {
info.put("password", password);
}
return (getConnection(url, info, Reflection.getCallerClass()));
}
// Worker method called by the public getConnection() methods.
private static Connection getConnection(
String url, java.util.Properties info, Class<?> caller) throws SQLException {
/*
* When callerCl is null, we should check the application's
* (which is invoking this class indirectly)
* classloader, so that the JDBC driver class outside rt.jar
* can be loaded from here.
*/
ClassLoader callerCL = caller != null ? caller.getClassLoader() : null;
synchronized(DriverManager.class) {
// synchronize loading of the correct classloader.
if (callerCL == null) {
callerCL = Thread.currentThread().getContextClassLoader();
}
}
if(url == null) {
throw new SQLException("The url cannot be null", "08001");
}
println("DriverManager.getConnection(\"" + url + "\")");
// Walk through the loaded registeredDrivers attempting to make a connection.
// Remember the first exception that gets raised so we can reraise it.
SQLException reason = null;
for(DriverInfo aDriver : registeredDrivers) {
// If the caller does not have permission to load the driver then
// skip it.
if(isDriverAllowed(aDriver.driver, callerCL)) {
try {
println(" trying " + aDriver.driver.getClass().getName());
Connection con = aDriver.driver.connect(url, info);
if (con != null) {
// Success!
println("getConnection returning " + aDriver.driver.getClass().getName());
return (con);
}
} catch (SQLException ex) {
if (reason == null) {
reason = ex;
}
}
} else {
println(" skipping: " + aDriver.getClass().getName());
}
}
// if we got here nobody could connect.
if (reason != null) {
println("getConnection failed: " + reason);
throw reason;
}
println("getConnection: no suitable driver found for "+ url);
throw new SQLException("No suitable driver found for "+ url, "08001");
}