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

请教一个问题, threadPoolExecutor.execute()能被 AOP 增强吗?

  •  1
     
  •   gengzi · Jan 18, 2021 · 2782 views
    This topic created in 1928 days ago, the information mentioned may be changed or developed.

    想在线程执行前,执行后,做一些事情

    8 replies    2021-01-19 11:21:44 +08:00
    zxlzy
        1
    zxlzy  
       Jan 18, 2021
    不行,只能是 Spring 代理的类,但是你可以通过继承 ThreadPoolExecutor, 然后重载 execute() 方法实现
    senninha
        2
    senninha  
       Jan 18, 2021
    ASM 插入逻辑生成字节码,然后 redefine 。
    fantastM
        3
    fantastM  
       Jan 18, 2021   ❤️ 1
    > 想在线程执行前,执行后,做一些事情

    ThreadPoolExecutor 内部提供了两个钩子方法 beforeExecute(Thread, Runnable) 和 afterExecute(Runnable, Throwable),正好符合你的需求。具体的看源码就清楚了 https://github.com/openjdk/jdk/blob/jdk8-b21/jdk/src/share/classes/java/util/concurrent/ThreadPoolExecutor.java#L1098-L1130
    hangszhang
        4
    hangszhang  
       Jan 18, 2021
    有钩子啊, 继承 ThreadPoolExecutor 之后实现就好了
    itechify
        5
    itechify  
    PRO
       Jan 18, 2021 via Android
    thread/task 用 abstract 封装成 base thread,里面加个 abstract 的 before 方法,run 方法重载先执行 before 再执行具体的 execute 方法。最后具体子类实现 before ?
    随便想想,不知道可不可
    gengzi
        6
    gengzi  
    OP
       Jan 19, 2021
    @zxlzy
    @senninha
    @fantastM
    @hangszhang
    @oneisall8955
    主要是想,不修改之前的逻辑,也能增强原有的方法。感谢各位大佬的思路,我去瞅瞅
    eaglewangl37670
        7
    eaglewangl37670  
       Jan 19, 2021
    @fantastM 学到了,感谢老哥
    fantastM
        8
    fantastM  
       Jan 19, 2021
    @eaglewangl37670 #7 不妨看看我博客里的这篇文章,对线程池的源码分析得更多 :)

    https://blog.fantasticmao.cn/2020/10/01/java-threadpoolexecutor-源码分析 /
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   807 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 20:34 · PVG 04:34 · LAX 13:34 · JFK 16:34
    ♥ Do have faith in what you're doing.