JAVA’s multithreading feature is always briefed about in the introduction of JAVA. The typical tutorials on thread creation process and the all famous bank withdrawal example offer little about a practical approach to problem solving using multithreading. In this post, I will brief about a problem I faced in one of my projects and applied multithreading to solve it. Before I proceed, I agree and appreciate your thoughts that the problem could have been solved in another way. I am highlighting what I applied and looked best to solve my problem.
- It’s a J2EE application consisting of Struts-Spring-JDBC.
- There is a screen that displays data about an entity. Data comprises of varied sources (5 to 6).
- For each source, there is a stored procedure that fetches data from the database.
- Stored procedures are independent.
- An initial setup was giving satisfactory response times.
- As the DB and processes grew in the system, the load on DB increased.
- Stored procedure started responding slowly due to heavy load on the system.
- Queries were optimized but response time remained high.
Solution: Split the requests in parts and process in parallel.
- Get a single request to the Struts action.
- Create multiple threads.
- Process the stored procedures independently in parallel.
- Load: Decide the number of threads you want to process in parallel. It should not be too high that it impacts other processes at the DB end.
- Return After All Complete: As per the current implementation; the user sees all data at once. Hence, the struts action must return to screen after all stored procedures have completed. This will prevent extra changes.
Implementation: Demonstrating with 2 threads parallel processing.
- Create a class that implement Runnable interface. I could not extend Thread class as I had to extend another project specific class.
- This will call the DB service that calls stored procedure.
- Rest all is grey matter for this post as its project and framework specific implementation of how to process DB request and responses.
- Next, create threads objects for class created in pointer#1.
- Start the threads.
- Join each of the created thread with the struts action thread.
- This will ensure that the struts action thread will not execute further till all parallel processing threads have completed.
- Note: The response time of screen will be difference of start time for first stored procedure to the end time of last stored procedure.
- A better approach can be AJAX implementation to show results as particular request completes.
Code Sample: Since I implemented this solution at my workplace; I cannot share the source. But I have created a demonstration sample at my github repository. The code comments are self-explanatory. Please refer to classes ThreadJoinCore & WorkerThreadOne.