// If the proxy class defined by the given loader implementing // the given interfaces exists, this will simply return the cached copy; // otherwise, it will create the proxy class via the ProxyClassFactory return proxyClassCache.get(loader, interfaces); }
public V get(K key, P parameter) { //要求参数,传进来的接口不能为空 Objects.requireNonNull(parameter); //清除过期的缓存 expungeStaleEntries(); //将ClassLoader包装成CacheKey, 作为一级缓存的key ObjectcacheKey= CacheKey.valueOf(key, refQueue);
// lazily install the 2nd level valuesMap for the particular cacheKey //获取得到二级缓存,用ConcurrentMap接受,保证线程安全 ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey); if (valuesMap == null) { //以CAS方式放入, 如果不存在则放入,否则返回原先的值 ConcurrentMap<Object, Supplier<V>> oldValuesMap = map.putIfAbsent(cacheKey, valuesMap = newConcurrentHashMap<>()); if (oldValuesMap != null) { valuesMap = oldValuesMap; } }
// create subKey and retrieve the possible Supplier<V> stored by that // subKey from valuesMap //根据代理类实现的接口数组 来生成二级缓存key并检索 ObjectsubKey= Objects.requireNonNull(subKeyFactory.apply(key, parameter)); //这里通过subKey获取到二级缓存的值 Supplier<V> supplier = valuesMap.get(subKey); Factoryfactory=null;
while (true) {//死循环,命中缓存就直接返回结果,不然就创建代理对象然后返回 if (supplier != null) { // supplier might be a Factory or a CacheValue<V> instance //在这里supplier可能是一个Factory也可能会是一个CacheValue //命中缓存就直接返回结果,不然就创建代理对象 Vvalue= supplier.get(); if (value != null) { return value; } } // else no supplier in cache // or a supplier that returned null (could be a cleared CacheValue // or a Factory that wasn't successful in installing the CacheValue)
// lazily construct a Factory if (factory == null) { //新建一个Factory实例作为subKey对应的值 factory = newFactory(key, parameter, subKey, valuesMap); }
这是WeakCache缓存类,非常复杂,我们只需关注 V value = supplier.get();这里supplier可能是一个Factory也可能会是一个CacheValue,如果命中缓存就直接返回结果结束循环 不然再次循环的时候 factory = new Factory(key, parameter, subKey, valuesMap); supplier = factory; 这个时候 V value = supplier.get();,其实调的是Factory.get()方法:
@Override publicsynchronized V get() { // serialize access // re-check Supplier<V> supplier = valuesMap.get(subKey); if (supplier != this) { // something changed while we were waiting: // might be that we were replaced by a CacheValue // or were removed because of failure -> // return null to signal WeakCache.get() to retry // the loop returnnull; } // else still us (supplier == this)
// create new value Vvalue=null; try { value = Objects.requireNonNull(valueFactory.apply(key, parameter)); } finally { if (value == null) { // remove us on failure valuesMap.remove(subKey, this); } } // the only path to reach here is with non-null value assert value != null;
// wrap value with CacheValue (WeakReference) CacheValue<V> cacheValue = newCacheValue<>(value);
// put into reverseMap reverseMap.put(cacheValue, Boolean.TRUE);
// try replacing us with CacheValue (this should always succeed) if (!valuesMap.replace(subKey, this, cacheValue)) { thrownewAssertionError("Should not reach here"); }
// successfully replaced us with new CacheValue -> return the value // wrapped by it return value; }
该get()方法,主要是 通过valueFactory创建代理类后 将代理类包装为CacheValue类,并将valuesMap缓存中对应代理类的Supplier替换为包装后的CacheValue,这样后面就可以直接调用CacheValue的get方法来获取代理类 其中 value = Objects.requireNonNull(valueFactory.apply(key, parameter));此处valueFactory我们来看下它是怎么过来的
// If the proxy class defined by the given loader implementing // the given interfaces exists, this will simply return the cached copy; // otherwise, it will create the proxy class via the ProxyClassFactory return proxyClassCache.get(loader, interfaces); } ... }
终于找到来源proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory()); 那valueFactory.apply(key, parameter),parameter参数是目标类实现的接口Class对象 ,其实调到是ProxyClassFactory.apply()方法:
privatestaticfinalclassProxyClassFactory implementsBiFunction<ClassLoader, Class<?>[], Class<?>> { // prefix for all proxy class names //代理类名称前缀 privatestaticfinalStringproxyClassNamePrefix="$Proxy";
// next number to use for generation of unique proxy class names //用原子类来生成代理类的序号, 以此来确定唯一的代理类 privatestaticfinalAtomicLongnextUniqueNumber=newAtomicLong();
@Override public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
Map<Class<?>, Boolean> interfaceSet = newIdentityHashMap<>(interfaces.length); for (Class<?> intf : interfaces) { /* * Verify that the class loader resolves the name of this * interface to the same Class object. */ Class<?> interfaceClass = null; try { //验证intf是否可以由指定的类加载进行加载 interfaceClass = Class.forName(intf.getName(), false, loader); } catch (ClassNotFoundException e) { } if (interfaceClass != intf) { thrownewIllegalArgumentException( intf + " is not visible from class loader"); } /* * Verify that the Class object actually represents an * interface. */ //验证intf是否是一个接口 if (!interfaceClass.isInterface()) { thrownewIllegalArgumentException( interfaceClass.getName() + " is not an interface"); } /* * Verify that this interface is not a duplicate. */ //验证intf在数组中是否有重复 if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) { thrownewIllegalArgumentException( "repeated interface: " + interfaceClass.getName()); } } //生成代理类的包名 StringproxyPkg=null; // package to define proxy class in //生成代理类的访问标志, 默认是public final的 intaccessFlags= Modifier.PUBLIC | Modifier.FINAL;
/* * Record the package of a non-public proxy interface so that the * proxy class will be defined in the same package. Verify that * all non-public proxy interfaces are in the same package. */ for (Class<?> intf : interfaces) { intflags= intf.getModifiers(); //如果接口的访问标志不是public, 那么生成代理类的包名和接口包名相同 if (!Modifier.isPublic(flags)) { accessFlags = Modifier.FINAL; Stringname= intf.getName(); intn= name.lastIndexOf('.'); Stringpkg= ((n == -1) ? "" : name.substring(0, n + 1)); if (proxyPkg == null) { proxyPkg = pkg; } elseif (!pkg.equals(proxyPkg)) { thrownewIllegalArgumentException( "non-public interfaces from different packages"); } } } //如果接口访问标志都是public的话, 那生成的代理类都放到默认的包下:com.sun.proxy if (proxyPkg == null) { // if no non-public proxy interfaces, use com.sun.proxy package proxyPkg = ReflectUtil.PROXY_PACKAGE + "."; }
/* * Choose a name for the proxy class to generate. */ //生成代理类的序号 longnum= nextUniqueNumber.getAndIncrement(); //生成代理类的全限定名, 包名+前缀+序号, 例如:com.sun.proxy.$Proxy0.这个就是我们debug经常看到的 StringproxyName= proxyPkg + proxyClassNamePrefix + num;
/* * Generate the specified proxy class. */ // 用ProxyGenerator来生成字节码, 该类放在sun.misc包下 !!! byte[] proxyClassFile = ProxyGenerator.generateProxyClass( proxyName, interfaces, accessFlags); try { //根据二进制文件生成相应的Class实例 return defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length); } catch (ClassFormatError e) { /* * A ClassFormatError here means that (barring bugs in the * proxy class generation code) there was some other * invalid aspect of the arguments supplied to the proxy * class creation (such as virtual machine limitations * exceeded). */ thrownewIllegalArgumentException(e.toString()); } } }