Introduction to Multi-Threading
In March of 2010 I was interviewed by Janice Heiss from Oracle (http://java.sun.com/developer/technicalArticles/Interviews/community/yakov_qa_2010.html), and she asked me to name the Java class I couldn’t live without. I didn’t think twice: Thread. This is where the power of Java resides. There are books devoted to Java threads, which give you amazing power and flexibility when it comes to building highly available, scalable, and responsive applications capable of processing thousands of concurrent requests of various types.
Up until now you’ve been creating Java programs that were executing code sequentially. But the main power of Java lies in its ability to do things in parallel, or, as they say, to run multiple threads of execution. As always, going through a practical use case is the best way to understand this feature.
Let’s discuss a program that should display market news and information about the user’s stock portfolio in the same window. While the market news feed is coming from a remote computer, stock portfolio data are retrieved from the database and may be located on the local machine.
Suppose it takes five seconds to get the market news and only three seconds to get the portfolio data. If you run these two tasks sequentially (one after another), you need eight seconds to complete the job.
But market news doesn’t depend on your portfolio data and these two tasks can run in parallel. They run on different computers and use ...