javathreadpoolexecutortemplate-method-pattern

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:

So my QUESTIONS are:


Solution

  • 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.