如何在多个子类中仅重写一次ThreadPoolExecutor的execute方法
问题背景
现有Java代码结构如下:
// 来自Java标准库 class ThreadPoolExecutor {} class ScheduledThreadPoolExecutor extends ThreadPoolExecutor {} // 子类 interface Enhance { default Runnable enhanceTask(Runnable command) { // 包装Runnable逻辑 ... } } class CommonThreadPoolExecutor extends ThreadPoolExecutor implements Enhance {} class CommonScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor implements Enhance {}
要增强ThreadPoolExecutor的execute方法,目前必须在两个子类中重复编写完全相同的重写代码:
class CommonThreadPoolExecutor extends ThreadPoolExecutor implements Enhance { @Override public void execute(@NonNull Runnable command) { Runnable runnable = enhanceTask(command); super.execute(runnable); } } class CommonScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor implements Enhance { @Override public void execute(@NonNull Runnable command) { Runnable runnable = enhanceTask(command); super.execute(runnable); } }
要求最终实例仍可赋值给ThreadPoolExecutor或ScheduledThreadPoolExecutor,如何实现仅编写一次execute方法的增强逻辑?
解决方案
方案1:提取增强逻辑到工具类(最小改动)
将核心增强逻辑抽离到静态工具类,两个子类的execute方法仅需调用工具方法,避免重复编写业务逻辑:
定义工具类:
public class EnhanceHelper { public static Runnable applyEnhance(Runnable command, Enhance enhancer) { return enhancer.enhanceTask(command); } }
修改子类代码:
class CommonThreadPoolExecutor extends ThreadPoolExecutor implements Enhance { @Override public void execute(@NonNull Runnable command) { super.execute(EnhanceHelper.applyEnhance(command, this)); } } class CommonScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor implements Enhance { @Override public void execute(@NonNull Runnable command) { super.execute(EnhanceHelper.applyEnhance(command, this)); } }
该方案保留原有类结构,仅抽离重复逻辑,代码改动极小,且实例可正常赋值给对应的父类类型。
方案2:使用CGLIB动态代理(彻底消除子类重写)
借助CGLIB动态代理技术,无需修改原有子类,通过生成代理类统一增强execute方法:
首先引入CGLIB依赖(Maven):
<dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.3.0</version> </dependency>
编写代理工厂:
import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; public class ThreadPoolEnhancerProxy { public static <T extends ThreadPoolExecutor & Enhance> T createEnhancedPool(T originalPool) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(originalPool.getClass()); enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> { // 仅拦截execute方法 if ("execute".equals(method.getName()) && args.length == 1 && args[0] instanceof Runnable) { args[0] = originalPool.enhanceTask((Runnable) args[0]); } return proxy.invokeSuper(obj, args); }); // 根据原始实例的构造参数生成代理(需根据实际构造方法调整) return (T) enhancer.create( originalPool.getClass().getConstructors()[0].getParameterTypes(), originalPool.getClass().getConstructors()[0].getParameters() ); } }
使用示例:
// 创建原始实例 CommonThreadPoolExecutor commonPool = new CommonThreadPoolExecutor(...); CommonScheduledThreadPoolExecutor scheduledPool = new CommonScheduledThreadPoolExecutor(...); // 生成增强代理实例,可直接赋值给父类类型 ThreadPoolExecutor enhancedPool = ThreadPoolEnhancerProxy.createEnhancedPool(commonPool); ScheduledThreadPoolExecutor enhancedScheduledPool = ThreadPoolEnhancerProxy.createEnhancedPool(scheduledPool);
该方案无需修改原有子类,所有增强逻辑集中在代理工厂,一次编写即可作用于所有符合条件的线程池子类。
方案3:抽象模板类(优化继承体系)
若后续可能新增更多ThreadPoolExecutor子类,可创建抽象模板类封装增强逻辑,让业务子类继承模板类:
abstract class EnhancedThreadPoolTemplate extends ThreadPoolExecutor implements Enhance { // 构造方法需与父类保持一致 public EnhancedThreadPoolTemplate(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } @Override public void execute(@NonNull Runnable command) { super.execute(enhanceTask(command)); } } // 修改CommonThreadPoolExecutor继承模板类 class CommonThreadPoolExecutor extends EnhancedThreadPoolTemplate {} // 针对ScheduledThreadPoolExecutor单独创建模板类 abstract class EnhancedScheduledThreadPoolTemplate extends ScheduledThreadPoolExecutor implements Enhance { public EnhancedScheduledThreadPoolTemplate(int corePoolSize, ThreadFactory threadFactory) { super(corePoolSize, threadFactory); } @Override public void execute(@NonNull Runnable command) { super.execute(enhanceTask(command)); } } class CommonScheduledThreadPoolExecutor extends EnhancedScheduledThreadPoolTemplate {}
该方案将每个父类对应的增强逻辑封装到独立模板中,业务子类只需继承模板即可获得增强能力,避免在每个子类中重复编写execute方法。
内容的提问来源于stack exchange,提问作者Manjiz
相关产品推荐
相关产品推荐

