This section contains some basic guidelines and tips for writing multithreaded code. These guidelines are similar to the design questions from Chapter 6 and Chapter 7 in that they form a starting point for design. They’re different, however, in that they’re not questions that lead to a clean design. Instead, they are rules of thumb for using threads in everyday code. Because they’re fairly general guidelines, I’ve interleaved applications to the banking example throughout this section.
It’s all too easy to say something such as:
I need to build a server that meets all these requirements and simultaneously scales to 150 clients.
Once you start trying to design for all the features in one shot, including thread safety and scalability, you’re doomed. Instead, the preceding situation is really three tasks that should be performed sequentially:
I need to build a server that meets all these requirements for a single client.
Then I need to make it threadsafe (so it can be used by three clients).
Then I need to make it scale.
If you approach the job of building a distributed application this way, you have a better chance of succeeding than if you try to satisfy all the requirements at once. Doing the latter is a sure way to fail.
The first rule of threading is that it’s better to be threadsafe than sorry. However, there’s a trade-off in thread management. First, synchronizing large blocks of ...