Java Reference
In-Depth Information
should not access these objects. (To make this easier, Swing provides the invokeLater
mechanism to schedule a Runnable for execution in the event thread.) Many concurrency
errors in Swing applications stem from improper use of these confined objects from another
thread.
Another common application of thread confinement is the use of pooled JDBC (Java Data-
base Connectivity) Connection objects. The JDBC specification does not require that
Connection objects be thread-safe. [9] In typical server applications, a thread acquires a
connection from the pool, uses it for processing a single request, and returns it. Since most
requests, such as servlet requests or EJB (Enterprise JavaBeans) calls, are processed syn-
chronously by a single thread, and the pool will not dispense the same connection to another
thread until it has been returned, this pattern of connection management implicitly confines
the Connection to that thread for the duration of the request.
Just as the language has no mechanism for enforcing that a variable is guarded by a lock, it
has no means of confining an object to a thread. Thread confinement is an element of your
program's design that must be enforced by its implementation. The language and core lib-
raries provide mechanisms that can help in maintaining thread confinement—local variables
and the ThreadLocal class—but even with these, it is still the programmer's responsibility
to ensure that thread-confined objects do not escape from their intended thread.
3.3.1. Ad-hoc Thread Confinement
Ad-hocthreadconfinement describes when the responsibility for maintaining thread confine-
ment falls entirely on the implementation. Ad-hoc thread confinement can be fragile because
none of the language features, such as visibility modifiers or local variables, helps confine
the object to the target thread. In fact, references to thread-confined objects such as visual
components or data models in GUI applications are often held in public fields.
The decision to use thread confinement is often a consequence of the decision to implement a
particular subsystem, such as the GUI, as a single-threaded subsystem. Single-threaded sub-
systems can sometimes offer a simplicity benefit that outweighs the fragility of ad-hoc thread
confinement. [10]
A special case of thread confinement applies to volatile variables. It is safe to perform read-
modify-write operations on shared volatile variables as long as you ensure that the volatile
variable is only written from a single thread. In this case, you are confining the modification
to a single thread to prevent race conditions, and the visibility guarantees for volatile vari-
ables ensure that other threads see the most up-to-date value.
Search WWH ::




Custom Search