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

Example of Worker Thread pattern



- Take note on what resource needs to be protected
requestQueueis the one that needs to be protected
- Add synchronized keyword on the method that can access the resource
putRequest()andtakeRequest()
- Apply Guard & Suspension condition on the while statement
while( ... )
- Add wait() inside the while loop
- Add notifyAll() on the end of the method


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


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
- Improved responsiveness
- If invocation and execution isn’t separated, the execution should be hold back until invocation is completed.
- Scheduling
- Regardless of the order of invocation, we can customize the order of execution
- Ability to cancel and repeat
- We can cancel after invocation before execution
- Distributed processing
- The invocation computer and execution computer doesn’t have to be on the same computer
Creating synchronize method
- Take note on what resource needs to be protected
- Add synchronized keyword on the method that can access the resource
- Apply Guard & Suspension condition on the while statement
- Add wait() inside the while loop
- 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

Leave a comment