Limit the Number of Objects a Thread Touches
The next tip in using threads is almost an emergent tip. If you use containers to mediate thread communication, use background threads to perform resource allocation and cleanup tasks, and
carefully limit the number of objects that serialization will visit, you'll notice something else happening. Each thread will only ever visit a small number of objects.
There's a slight exception to this. Since RMI reuses the same thread across multiple client requests, that thread may eventually wind up visiting many instances. But during any given remote method invocation, it will only visit a few.
This is an important and useful consequence. It's so important and so useful that it deserves to be a design guideline of its own instead of just a consequence of the others. If all of your threads touch only a few objects, then your code will be much easier to debug, and you can think about thread interaction problems such as deadlock. If, on the other hand, a given thread can execute any method in your code, then you'll have a hard time predicting when thread-interaction problems will occur and which threads caused a particular problem.
Post a comment