Java Reference
In-Depth Information
1.4. Threads are Everywhere
Even if your program never explicitly creates a thread, frameworks may create threads on
your behalf, and code called from these threads must be thread-safe. This can place a signi-
ficant design and implementation burden on developers, since developing thread-safe classes
requires more care and analysis than developing non-thread-safe classes.
Every Java application uses threads. When the JVM starts, it creates threads for JVM house-
keeping tasks (garbage collection, finalization) and a main thread for running the main
method. The AWT (Abstract Window Toolkit) and Swing user interface frameworks create
threads for managing user interface events. Timer creates threads for executing deferred
tasks. Component frameworks, such as servlets and RMI create pools of threads and invoke
component methods in these threads.
If you use these facilities—as many developers do—you have to be familiar with concur-
rency and thread safety, because these frameworks create threads and call your components
from them. It would be nice to believe that concurrency is an “optional” or “advanced” lan-
guage feature, but the reality is that nearly all Java applications are multithreaded and these
frameworks do not insulate you from the need to properly coordinate access to application
state.
When concurrency is introduced into an application by a framework, it is usually impossible
to restrict the concurrency-awareness to the framework code, because frameworks by their
nature make callbacks to application components that in turn access application state. Simil-
arly, the need for thread safety does not end with the components called by the framework—it
extends to all code paths that access the program state accessed by those components. Thus,
the need for thread safety is contagious.
Frameworks introduce concurrency into applications by calling application components from
framework threads. Components invariably access application state, thus requiring that all
code paths accessing that state be thread-safe.
The facilities described below all cause application code to be called from threads not man-
aged by the application. While the need for thread safety may start with these facilities, it
rarely ends there; instead, it ripples through the application.
Search WWH ::




Custom Search