Ch.08 – Worker Thread pattern

Published by

on

Worker threads are sometimes called as background thread, who keeps executing jobs pulled from job queue.

Class Diagram & Time Thread Diagram

Example of Worker Thread pattern

Main.java
ClientThread.java
Channel.java
  1. Take note on what resource needs to be protected
    • requestQueue is the one that needs to be protected
  2. Add synchronized keyword on the method that can access the resource
    • putRequest() and takeRequest()
  3. Apply Guard & Suspension condition on the while statement
    • while( ... )
  4. Add wait() inside the while loop
  5. Add notifyAll() on the end of the method
Request.java
WorkerThread.java
  • Polymorphism of the Request class
    • As WorkerThread doesn’t and doesn’t need to know what kind of Request it is executing, we can extend the Request class and provide it to the Channel which will be executed without any problem.
Class Diagram
Sequence Diagram

Invocation vs Execution

Normally when we run a method, the invocation and execution isn’t divide into two different ones. However, from patterns like Worker Thread pattern, or Thread-Per-Message , the method invocation and execution is differentiated.

Advantages of separation

  1. Improved responsiveness
    • If invocation and execution isn’t separated, the execution should be hold back until invocation is completed.
  2. Scheduling
    • Regardless of the order of invocation, we can customize the order of execution
  3. Ability to cancel and repeat
    • We can cancel after invocation before execution
  4. Distributed processing
    • The invocation computer and execution computer doesn’t have to be on the same computer

Creating synchronize method

  1. Take note on what resource needs to be protected
  2. Add synchronized keyword on the method that can access the resource
  3. Apply Guard & Suspension condition on the while statement
  4. Add wait() inside the while loop
  5. Add notifyAll() on the end of the method

Notes

  • In Spring framework, we as a programmer do not need to consider synchronization on accessing HttpServletRequest/HttpServletResponse. Each thread will have their own request/response respectively as the exclusive control is already done from the framework itself.

ThreadPoolExecutor

  • ThreadPoolExecutor is a class which manages the worker threads.
  • Can initialize the size of the thread pool
  • Can determine how to create the thread(beforehand or on-demand)
  • Can specify ThreadFactory when creating threads
  • Can customize Thread implementation, Queue implementation, etc

Reference

Leave a comment