0

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 is abstract
  • hook methods, such as beforeExecute(Thread t, Runnable r) and afterExecute(Runnable r, Throwable t), in ThreadPoolExecutor are concrete with empty method body, whereas hook methods in abstract class of template method pattern are abstract albeit the fact that both hook methods are protected indicating that they should be overridden 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?
4

1 回答 1

0

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.

于 2018-06-04T07:55:14.037 回答