Java Reference
In-Depth Information
B ENEFITS AND C AUTIONS
Java's ability to create and execute multiple threads allows the developer to build re-
sponsive, powerful applications. In particular, applications that perform significant
work but still need to respond to user input are good candidates for a multi-
threaded design. Another good nominee is an application that needs to respond to
end-user input from multiple interactive dialog boxes (the search utility in a word
processor, for example).
Other possibilities include applications that contain functions that can be
processed in parallel. In today's environment, production systems often have mul-
tiple CPUs. Breaking up your task into multiple functions that can run simultane-
ously allows the system to assign your work to multiple CPUs. The result will likely
be more work done in less time.
Some parallel functions are obvious (perhaps you have a data migration appli-
cation, and it can be structured to extract data from multiple tables simultane-
ously). Other times the opportunities require a little more thought (how can I
break up a single table extract function into multiple steps?). In any event, the ef-
fective use of threads can result in more efficient, more responsive applications.
Finally, some environments effectively define the threading model for you. For
example, if you are using a JEE application server (discussed in Chapter 15), it is
likely that the code you write will execute in a multi-threaded environment.
Still, it is important not to treat threads like a shiny new tool that should be
used with every project. As with any good thing, it is possible to get carried away
with using threads.
The use of multiple threads in an application can be a very difficult pro-
gramming model. It is up to you (the developer) to anticipate and prevent re-
source conflicts. In many cases, you even need to manage (schedule, start, stop,
and synchronize) threads so that they execute when required. Furthermore, an
application that contains a shared resource problem (for example, one thread
updates a counter, while another thread decrements it) is a very difficult appli-
cation to debug. In fact, the debugger can affect the symptoms of the problem
you are analyzing, since it runs in a thread of its own.
Thread implementations vary significantly across operating systems and vir-
tual machines. Some VMs use the native operating system thread mechanism,
whereas others create their own thread management logic in the VM. In the latter
case, multi-threaded performance is likely to be less than what you would expect.
Don't recreate an operating system using threads. It is unlikely that an average
developer can write process-management and context-switching logic that is
more effective than the process-management and context-switching logic built
into the operating system. The major advantage of threads is that the developer
Search WWH ::




Custom Search