Lesson 17Concurrency and Multithreading

Developing Java applications that implement concurrent processing gives you an 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 server of your organization.

Suppose it takes three seconds to get the market news and only one second to get the portfolio data. If you run these two tasks sequentially (one after another), you need four 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 different processors. If you can implement parallel processing, the total time should be less than four seconds (close to three seconds in the use case—the time it takes for the longer task to complete).

A Java program can start multiple threads of ...

Get Java Programming 24-Hour Trainer, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.