V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
git00ll
V2EX  ›  Java

请问一下 jdk proxy,为同一个接口生成多个代理类时,会有多个类产生吗

  •  
  •   git00ll · 2022-07-03 21:25:53 +08:00 · 1363 次点击
    这是一个创建于 635 天前的主题,其中的信息可能已经有所发展或是发生改变。

    例如如下代码,他将为接口 A 创建 3 个代理类,那么这 3 个代理类之间共享同一个 class 还是创建 3 个不同 class 。

    
    Proxy.newProxyInstance(loader, new Class[]{A.class}, new MyHandler1());
    Proxy.newProxyInstance(loader, new Class[]{A.class}, new MyHandler2());
    Proxy.newProxyInstance(loader, new Class[]{A.class}, new MyHandler3());
    
    

    因为在我的代码中会频繁为某个接口生成代理类,所以想问问上面这种使用方式会不会每次生成都会有新的 class 产生。 如果一直产生新 class 的话,时间长一定会 oom 的,去如果共享一个 class 就没有这个问题。

    5 条回复    2022-07-04 16:31:43 +08:00
    uselessVisitor
        1
    uselessVisitor  
       2022-07-03 21:45:21 +08:00
    不会 oom 的,proxy 我记得有 weakCache 的,除非你递归 proxy 了,spring 里到处都是 proxy 你看他 oom 了吗?
    git00ll
        2
    git00ll  
    OP
       2022-07-03 22:12:09 +08:00
    @beichenhpy 关键是 spring 中的 proxy 一般来说是一个接口对应一个 proxy ,有个上限。 我这边会为一个接口生成大量的 proxy ,数量可能会非常多
    qinxi
        3
    qinxi  
       2022-07-04 09:31:33 +08:00
    简单, 你把方法区(元空间)设置小一点. 循环生成 1 万个就知道了. 我觉得应该会 oom.
    hingbong
        4
    hingbong  
       2022-07-04 09:58:07 +08:00
    `java.lang.reflect.Proxy#getProxyClass0`看起来是根据了 classloader+接口做了缓存的
    Kould
        5
    Kould  
       2022-07-04 16:31:43 +08:00
    不会导致新 class 产生,其实基本是依照这个 class 结合 handler 生成一个新的代理对象。至于这些对象不使用后怎么处理就看 gc 了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2450 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 15:56 · PVG 23:56 · LAX 08:56 · JFK 11:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.