Multithreading and Multiplexing
After reading this chapter, you should:
understand what is meant by a thread (in a programming context);
appreciate the need for multithreaded programming;
be aware of typical circumstances under which multithreading might be
know how to implement threads in Java;
know how to implement locking of variables in Java;
be aware of the danger posed by deadlock;
know what Java methods to use in order to improve thread effi ciency and reduce
the likelihood of deadlock;
know how to implement a multithreaded server;
know how to implement a non-blocking server via multiplexing.
It is often the case nowadays that programs need to carry out more than one signifi -
cant task at the same time (i.e., 'concurrently'). For example, a GUI-driven program
may be displaying a background animation while processing the user's foreground
interactions with the interface, or a Web browser may need to download and display
the contents of a graphics fi le while rendering the rest of the associated Web page.
The popularity of client/server applications over the past decade has exacerbated
this demand enormously, with server programs sometimes having to process the
needs of several hundreds of clients at the same time.
Some years ago, each client that connected to a server would have caused a
new process to be spawned on the server. The problem with this approach is that
a fresh block of memory is set aside for each such process. While the number of
clients connecting to the server remained reasonably low, this presented no diffi -
culties. However, as the use of the Internet mushroomed, servers that created a
new process for each client would grind to a halt as hundreds, possibly thousands,
of clients attempted to access their services simultaneously. A way of signifi cantly
alleviating this problem is to use what are called threads , instead of processes.