Java动态代理深入解析(3)

/*
            * Verify that the Class object actually represents an
            * interface.
            */
            if (!interfaceClass.isInterface()) {
                throw new IllegalArgumentException(
                    interfaceClass.getName() + " is not an interface");
            }

/*
            * Verify that this interface is not a duplicate.
            */
            if (interfaceSet.contains(interfaceClass)) {
                throw new IllegalArgumentException(
                    "repeated interface: " + interfaceClass.getName());
            }
            interfaceSet.add(interfaceClass);

interfaceNames[i] = interfaceName;
        }

/*
        * Using string representations of the proxy interfaces as
        * keys in the proxy class cache (instead of their Class
        * objects) is sufficient because we require the proxy
        * interfaces to be resolvable by name through the supplied
        * class loader, and it has the advantage that using a string
        * representation of a class makes for an implicit weak
        * reference to the class.
        */
        List<String> key = Arrays.asList(interfaceNames);  //使用interfaces列表作为key缓存在cache里,也就是实现了相同interfaces的代理类只会创建加载一次

/*
        * Find or create the proxy class cache for the class loader.
        */
        Map<List<String>, Object> cache;
        synchronized (loaderToCache) {
            cache = loaderToCache.get(loader);
            if (cache == null) {
                cache = new HashMap<>();
                loaderToCache.put(loader, cache);
            }
            /*
            * This mapping will remain valid for the duration of this
            * method, without further synchronization, because the mapping
            * will only be removed if the class loader becomes unreachable.
            */
        }

/*
        * Look up the list of interfaces in the proxy class cache using
        * the key.  This lookup will result in one of three possible
        * kinds of values:
        *    null, if there is currently no proxy class for the list of
        *        interfaces in the class loader,
        *    the pendingGenerationMarker object, if a proxy class for the
        *        list of interfaces is currently being generated,
        *    or a weak reference to a Class object, if a proxy class for
        *        the list of interfaces has already been generated.
        */
     //看看缓存里有没有,如果有就直接取出来然后return,否则判断根据pendingGenerationMarker判断是否有其它线程正在生成当前的代理类,如果有则cache.wait()等待,如果没有则创建。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/0dab0fb138c3829c8bf6ef3b552a8a73.html