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;
}
}
synchronized移到了方法内的代码块中,也就是说不再是简单的锁定当前类加载器,而是锁定一个生成的对象。
那么这个充当锁的对象是如何生成的?
protected Object getClassLoadingLock(String className) {
Object lock = this;
if (parallelLockMap != null) {
Object newLock = new Object();
lock = parallelLockMap.putIfAbsent(className, newLock);
if (lock == null) {
lock = newLock;
}
}
return lock;
}
parallelLockMap是一个ConcurrentHashMap,putIfAbsent(K, V)方法查看K和V是否已经对应,是的话返回V,否则就将K,V对应起来,返回null。
第一个if判断里面的逻辑,一目了然:对每个className关联一个锁,并将这个锁返回。也就是说,将锁的粒度缩小了。只要类名不同,加载的时候就是完全并行的。这与ConcurrentHashMap实现里面的分段锁,目的是一样的。
我这里有2个问题希望读者思考一下:
1)为什么不直接用className这个字符串充当锁对象
2)为什么不是直接new一个Object对象返回,而是用一个map将className和锁对象缓存起来
上面的方法中还别有洞天,为什么要判断parallelLockMap是否为空,为什么还有可能返回this,返回this的话不就是又将当前类加载器锁住了吗。这里返回this,是为了向后兼容,因为以前的版本不支持并行。有疑问就看源码,
// Maps class name to the corresponding lock object when the current
// class loader is parallel capable.
// Note: VM also uses this field to decide if the current class loader
// is parallel capable and the appropriate lock object for class loading.
private final ConcurrentHashMap<String, Object> parallelLockMap;
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;
}
}
可见,对于parallelLockMap的处理一开始就分成了2种逻辑:如果将当前类加载器注册为并行类加载器,就为其赋值;否则就一直为null。
ParallelLoaders是ClassLoader的内部类