gengzi
V2EX  ›  Java

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

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

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

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

    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
    hangszhang
    Jan 18, 2021
    4
    有钩子啊, 继承 ThreadPoolExecutor 之后实现就好了
    itechify
    itechify
    Jan 18, 2021 via Android
    5
    thread/task 用 abstract 封装成 base thread,里面加个 abstract 的 before 方法,run 方法重载先执行 before 再执行具体的 execute 方法。最后具体子类实现 before ?
    随便想想,不知道可不可
    gengzi
    gengzi
    OP
    Jan 19, 2021
    6
    @zxlzy
    @senninha
    @fantastM
    @hangszhang
    @oneisall8955
    主要是想,不修改之前的逻辑,也能增强原有的方法。感谢各位大佬的思路,我去瞅瞅
    eaglewangl37670
    eaglewangl37670
    Jan 19, 2021
    7
    @fantastM 学到了,感谢老哥
    fantastM
    fantastM
    Jan 19, 2021
    8
    @eaglewangl37670 #7 不妨看看我博客里的这篇文章,对线程池的源码分析得更多 :)

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