V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
git00ll
V2EX  ›  Java

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

  •  
  •   git00ll · Jul 3, 2022 · 2084 views
    This topic created in 1394 days ago, the information mentioned may be changed or developed.

    例如如下代码,他将为接口 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 replies    2022-07-04 16:31:43 +08:00
    zm8m93Q1e5otOC69
        1
    zm8m93Q1e5otOC69  
       Jul 3, 2022
    不会 oom 的,proxy 我记得有 weakCache 的,除非你递归 proxy 了,spring 里到处都是 proxy 你看他 oom 了吗?
    git00ll
        2
    git00ll  
    OP
       Jul 3, 2022
    @beichenhpy 关键是 spring 中的 proxy 一般来说是一个接口对应一个 proxy ,有个上限。 我这边会为一个接口生成大量的 proxy ,数量可能会非常多
    qinxi
        3
    qinxi  
       Jul 4, 2022
    简单, 你把方法区(元空间)设置小一点. 循环生成 1 万个就知道了. 我觉得应该会 oom.
    hingbong
        4
    hingbong  
       Jul 4, 2022
    `java.lang.reflect.Proxy#getProxyClass0`看起来是根据了 classloader+接口做了缓存的
    Kould
        5
    Kould  
       Jul 4, 2022
    不会导致新 class 产生,其实基本是依照这个 class 结合 handler 生成一个新的代理对象。至于这些对象不使用后怎么处理就看 gc 了。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5217 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 03:55 · PVG 11:55 · LAX 20:55 · JFK 23:55
    ♥ Do have faith in what you're doing.