JDK动态代理源码分析

本文深入剖析JDK动态代理的工作原理,重点介绍了Proxy类的getProxyClass方法如何生成动态代理类,以及WeakCache缓存机制如何高效管理和更新这些代理类。

JDK动态代理建立在Java反射机制之上,在程序运行时对指定接口增强,降低接口的耦合性,被广泛应用Spring框架。本文将从Proxy的调用以及其缓存机制WeakCache介绍JDK动态代理的工作原理
在生成动态代理时,通常会调用Proxy的静态方法getProxyClass,在Proxy内部实际则是对getProxyClass0的简单包装

private static Class<?> getProxyClass0(ClassLoader loader,
                                       Class<?>... interfaces) {
    if (interfaces.length > 65535) {//代理接口数上限检查
        throw new IllegalArgumentException("interface limit exceeded");
    }
    return proxyClassCache.get(loader, interfaces);//缓存获取代理类
}

proxyClassCache作为Proxy内部私有成员变量其定义如下:

private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
    proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

定义WeakCache作为代理类缓存容器,先对WeakCache详细分析,其相应的成员变量如下:

private final ReferenceQueue<K> refQueue
    = new ReferenceQueue<>();//引用队列,与弱引用关联,GC后可用于更新无效缓存
// the key type is Object for supporting null key
private final ConcurrentMap<Object, ConcurrentMap<Object, Supplier<V>>> map
    = new ConcurrentHashMap<>(); //缓存实际对应的map
private final ConcurrentMap<Supplier<V>, Boolean> reverseMap
    = new ConcurrentHashMap<>();  //有效代理类的缓存
private final BiFunction<K, P, ?> subKeyFactory;  //缓存中Key的生成工厂
private final BiFunction<K, P, V> valueFactory;   //缓存中Value的生成工厂

WeakCache使用二级缓存来缓存动态代理的生成类,Key-value含义如下这里写图片描述

利用GC更新过期缓存

WeakCache缓存背后的机制是通过弱引用,以及关联引用队列将为被GC的value对象有效的缓存,而当JVM内存不够时,又可以回收缓存中弱引用对象进而回收过期缓存,包装了缓存机制的健壮性

private void expungeStaleEntries() {
    CacheKey<K> cacheKey;
    while ((cacheKey = (CacheKey<K>)refQueue.poll()) != null) {//引用队列中有对象被GC
        cacheKey.expungeFrom(map, reverseMap);//清除缓存过期缓存
    }
}

更新过期缓存

void expungeFrom(ConcurrentMap<?, ? extends ConcurrentMap<?, ?>> map,
                 ConcurrentMap<?, Boolean> reverseMap) {
    ConcurrentMap<?, ?> valuesMap = map.remove(this);//map中将被回收的key-value移除
    if (valuesMap != null) {//有相应的过期缓存代理类
        for (Object cacheValue : valuesMap.values()) {
            reverseMap.remove(cacheValue);//更新缓存辅助类,以方便确定有效缓存类的数量
        }
    }
}

存取缓存流程

public V get(K key, P parameter) {
    Objects.requireNonNull(parameter);//参数检查
    expungeStaleEntries();//缓存更新
    Object cacheKey = CacheKey.valueOf(key, refQueue);//将缓存key与引用队列关联
    ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);//获取一级缓存
    if (valuesMap == null) {
        ConcurrentMap<Object, Supplier<V>> oldValuesMap
            = map.putIfAbsent(cacheKey,
                              valuesMap = new ConcurrentHashMap<>());
        if (oldValuesMap != null) {
            valuesMap = oldValuesMap;
        }
    }
    Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));//根据keyFactory生成对应的key   (1)
    Supplier<V> supplier = valuesMap.get(subKey);//尝试获取缓存的代理类的工厂
    Factory factory = null;
    while (true) {
        if (supplier != null) {
            V value = supplier.get();//获取缓存代理类(2)
            if (value != null) {
                return value;
            }
        }
        if (factory == null) {
            factory = new Factory(key, parameter, subKey, valuesMap);//初始化工厂
        }
        if (supplier == null) {//初始化缓存类工厂
            supplier = valuesMap.putIfAbsent(subKey, factory);
            if (supplier == null) {
                // successfully installed Factory
                supplier = factory;
            }
        } else {//更新缓存类工厂
            if (valuesMap.replace(subKey, supplier, factory)) {
                supplier = factory;
            } else {
                // retry with current supplier
                supplier = valuesMap.get(subKey);
            }
        }
    }
}

WeakCache获取的代理类时,先更新引用队列,然后以需获取代理类的classload与引用队列关联并包装为对应一级缓存key。然后通过缓存keyFactory工厂的apply生成缓存代理类工厂(由Proxy内部类KeyFactory实现)

public Object apply(ClassLoader classLoader, Class<?>[] interfaces) {
    switch (interfaces.length) {//根据接口,生成缓存Key对象
        case 1: return new Key1(interfaces[0]); 
        case 2: return new Key2(interfaces[0], interfaces[1]);
        case 0: return key0;
        default: return new KeyX(interfaces);
    }
}

缓存key工厂根据缓存代理代理类接口生成对应的key对象,以作为而二级缓存去获取缓存类工厂,成功更新到缓存工厂之后,缓存工厂将从二级缓存获取代理类,流程如下:

public synchronized V get() {
    Supplier<V> supplier = valuesMap.get(subKey);
    if (supplier != this) {//再次更新缓存key工厂
        return null;
    }
    V value = null;
    try {
        value = Objects.requireNonNull(valueFactory.apply(key, parameter));//value工厂生成缓存类
    } finally {
        if (value == null) { // remove us on failure
            valuesMap.remove(subKey, this);//获取失败,移除缓存key
        }
    }
    assert value != null;
    CacheValue<V> cacheValue = new CacheValue<>(value);//缓存类包装
    reverseMap.put(cacheValue, Boolean.TRUE);//存入缓存辅助类
    if (!valuesMap.replace(subKey, this, cacheValue)) {//更新supplied为cacheValue,(在JVM GC之前直接获取,不再通过反射生成)
        throw new AssertionError("Should not reach here");
    }
    return value;
}

缓存工厂获取代理类时,首先更新工厂以确保线程安全性,然后由相应的valueFactory生成相应代理类,这里需要说明的是valueFactory生成代理类成功之后调用valuesMap.replace(subKey, this, cacheValue)将supplier替换为cacheValue以便后续缓存获取,而不是重新生成。
缓存代理类的生成

public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
        Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
        for (Class<?> intf : interfaces) {//检查接口合法性
            Class<?> interfaceClass = null;
            try {
                interfaceClass = Class.forName(intf.getName(), false, loader);
            } catch (ClassNotFoundException e) {
            }
            if (interfaceClass != intf) {
                throw new IllegalArgumentException(
                    intf + " is not visible from class loader");
            }
            if (!interfaceClass.isInterface()) {
                throw new IllegalArgumentException(
                    interfaceClass.getName() + " is not an interface");
            }
            if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
                throw new IllegalArgumentException(
                    "repeated interface: " + interfaceClass.getName());
            }
        }
        String proxyPkg = null;     // package to define proxy class in
        int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
        for (Class<?> intf : interfaces) {
            int flags = intf.getModifiers();
            if (!Modifier.isPublic(flags)) {//含非公共接口,匹配特定包名
                accessFlags = Modifier.FINAL;
                String name = intf.getName();
                int n = name.lastIndexOf('.');
                String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
                if (proxyPkg == null) {
                    proxyPkg = pkg;
                } else if (!pkg.equals(proxyPkg)) {//非公共接口不能在不同包
                    throw new IllegalArgumentException(
                        "non-public interfaces from different packages");
                }
            }
        }

        if (proxyPkg == null) {//均为代理接口均为接口默认包名
            proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
        }
        long num = nextUniqueNumber.getAndIncrement();
        String proxyName = proxyPkg + proxyClassNamePrefix + num;
        byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
            proxyName, interfaces, accessFlags);//生成对应代理类二进制
        try {
            return defineClass0(loader, proxyName,
                                proxyClassFile, 0, proxyClassFile.length);//定义代理类
        } catch (ClassFormatError e) {

            throw new IllegalArgumentException(e.toString());
        }
    }
}

代理类的生成主要由Java反射机制,并有jvm的本地方法defineClass0实现。ValueFactory生成代理类之后,将代理类缓存更新,以便后续使用

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值