Java Reference
In-Depth Information
gramming is setting up the right protections to ensure that the memory shared by the multiple
threads does not introduce new and subtle bugs.
The Basics
We've already seen a situation where it might be nice to have multiple threads running. The
kinds of cases you hear a lot about these days are when you have a lot of work that can be
broken down into parallel computations, and you place each of the computations in a separate
thread. We haven't done anything like that, but we have encountered a place where we are
making calls that could take a (relatively) long time to complete. It would be nice if we could
make those calls, do some other work while the calls were completing, and then come back to
them when we had finished our other work to get the results.
We saw possible examples of this in Chapter 9 . Calls that go across a network can take a lot
of time (for a computer), and if we can find something else to do while those calls are being
made, we can make better use of our computing resources. But using a remote procedure call
mechanism means that the call across the network looks like a local method call, which in turn
means that we need to wait for the call to complete before we can do something else. There
are some who have argued that this shows a basic weakness in the RPC paradigm, and that this
approach to distributed systems should be abandoned in favor of some sort of message-orien-
ted system. I will not go into that debate here, other than to say that with the use of concurrent
programming techniques, such arguments don't really hold water. [ 40 ]
Waiting for an RPC call to complete can cost us a lot of performance unless we make the call
in a separate thread. If we create a new thread to do the RMI call, we can let that thread wait
for the answer while we have a different thread do something else. This sort of approach helps
even if we are on a single-core processor, where only one thread is running at a time. While
the RMI call is pending, the other thread can be scheduled and run.
The simplest way to do this is to create a class that extends the base system class
java.lang.Thread . Such a class will inherit a start() method that will kick off a thread,
running the run() method that is also inherited from the base Thread class.
To see how this works, let's go back to our StatReporterImpl class. One of the things that
class does is call a remote StatRecorder object to get the rosters for a team. The StatRe-
porterImpl object can then use the roster to get initial information, such as the player ID,
for those players in a game that the StatReporterImpl object is going to report to the
StatRecorder . In our original implementation, the StatReporterImpl object made a call to
Search WWH ::

Custom Search