java - Does the ThreadPoolExecutor Apply the Template Pattern?
问题描述
There are 2 hook methods in the ThreadPoolExecutor.
This technique makes me think of the template method pattern, where there are hook methods in the abstract
class. However, the hook methods in the abstract class of template method do differ from that of ThreadPoolExecutor
in that:
ThreadPoolExecutor
class is concrete, whereas the class defining the hook methods in the template method pattern isabstract
- hook methods, such as
beforeExecute(Thread t, Runnable r)
andafterExecute(Runnable r, Throwable t)
, inThreadPoolExecutor
are concrete with empty method body, whereas hook methods inabstract
class of template method pattern areabstract
albeit the fact that both hook methods areprotected
indicating that they should beoverridden
in their subclasses
So my QUESTIONS are:
- does the
ThreadPoolExecutor
belong to template method pattern at all? - Is the hook method per se. an independent technique from the template method pattern?
解决方案
Personally, I would say yes, because the ThreadPoolExecutor pre-defines a set of commands that cannot be altered when subclassing as it's marked as final
. See #runWorker
.
This is the template: First beforeExecute
, second task.run
, third afterExecute
.
final void runWorker(Worker w) {
// ... snip
beforeExecute(wt, task);
try {
task.run();
}
...
} finally {
afterExecute(task, thrown);
}
// ... snip
}
It leaves some parts of the implementation to the subclass, beforeExecute
, afterExecute
.
But yes, I'm aware there can be discussion as in this case the class only has hooks (not marked as abstract so permitted but not a requirement) to control subclasses.
推荐阅读
- asp.net-core-webapi - 会话存储在 asp.net 核心 web api 中返回 null
- javascript - 复选框返回 null
- mongodb - 使用 FindOne 和 $natural 从 GoLang 中的 mongodb 获取最后插入的元素
- python - 无法安装 Ball 模块
- powershell - 如何在powershell中返回具有相同扩展名但包含特定名称结尾的文件?
- amazon-web-services - 在 Terraform 中使用模块将 EIP 关联到我的 NAT 网关后出现错误
- python-3.x - 使用给出错误“ValueError:加密/解密失败”的加密包解密数据。
- json - 尝试将 JSON 文件加载到数据框中时出现 UnicodeDecodeError
- date - 从日期中减去的正确顺序是什么
- c++ - 为模板专业化方法创建 gmock 测试