When multiple threads run as part of a single application, or a JVM, we
have multiple tasks or operations running concurrently. A concurrent appli-
cation makes use of multiple threads or concurrent flows of execution.
On a single processor, these concurrent tasks are often multiplexed or
multitasked. That is, the processor rapidly switches between the context of
each flow of execution. However, only one thread, and hence only one flow
of execution, is performed at any given instance. On a multicore processor,
more than one flow of execution (thread) is performed at any given instance.
That number depends on the number of cores available on the processor,
and the number of concurrent threads for an application depends on the
number of cores associated with its process.
1.2 The Power of Concurrency
We’re interested in concurrency for two reasons: to make an application
responsive/improve the user experience and to make it faster.
Making Apps More Responsive
When we start an application, the main thread of execution often takes on
multiple responsibilities sequentially, depending on the actions we ask it to
perform: receive input from a user, read from a file, perform some calcula-
tions, access a web service, update a database, display a response to the
user, and so on. If each of these operations takes only fractions of a second,
then there may be no real need to introduce additional flows of execution;
a single thread may be quite adequate to meet the needs.
In most nontrivial applications, however, these operations may not be that
quick. Calculations may take anywhere from a couple of seconds to a few
minutes. Requests for data from that web service may encounter network
dela y s, so the th read waits fo r t h e r espon se t o a rriv e . W hile this is h a ppen i ng,
there’s no way for the users of the application to interact with or interrupt
the application because the single thread is held on some operation to finish.
Let’s consider an example that illustrates the need for more than one thread
and how it impacts responsiveness. We often time events, so it would be
nice to have stopwatch application. We can click a button to start the watch,
and it will run until we click the button again. A naively written
1
bit of code
for this is shown next (only the action handler for the button is shown; you
can download the full program from the website for this book):
1. In the examples, we’ll simply let exceptions propagate instead of logging or handling
them—but be sure to handle exceptions properly in your production code.
2 • Chapter 1. The Power and Perils of Concurrency