Java Reference
In-Depth Information
will necessarily be accessed by multiple threads. Servlets need not use synchronization when
calling set-Attribute and getAttribute , but they may have to use synchronization
when using the objects stored in the ServletContext . These objects are owned by the
application; they are being stored for safekeeping by the servlet container on the application's
behalf. Like all shared objects, they must be shared safely; in order to prevent interference
from multiple threads accessing the same object concurrently, they should either be thread-
safe, effectively immutable, or explicitly guarded by a lock. [1]
4.2. Instance Confinement
If an object is not thread-safe, several techniques can still let it be used safely in a multith-
readed program. You can ensure that it is only accessed from a single thread (thread confine-
ment), or that all access to it is properly guarded by a lock.
Encapsulation simplifies making classes thread-safe by promoting instance confinement , of-
ten just called confinement [CPJ 2.3.3]. When an object is encapsulated within another ob-
ject, all code paths that have access to the encapsulated object are known and can be therefore
be analyzed more easily than if that object were accessible to the entire program. Combining
confinement with an appropriate locking discipline can ensure that otherwise non-thread-safe
objects are used in a thread-safe manner.
Encapsulating data within an object confines access to the data to the object's methods, mak-
ing it easier to ensure that the data is always accessed with the appropriate lock held.
Confined objects must not escape their intended scope. An object may be confined to a class
instance (such as a private class member), a lexical scope (such as a local variable), or a
thread (such as an object that is passed from method to method within a thread, but not sup-
posed to be shared across threads). Objects don't escape on their own, of course—they need
help from the developer, who assists by publishing the object beyond its intended scope.
PersonSet in Listing 4.2 illustrates how confinement and locking can work together to
make a class thread-safe even when its component state variables are not. The state of Per-
sonSet is managed by a HashSet , which is not thread-safe. But because mySet is private
and not allowed to escape, the HashSet is confined to the PersonSet . The only code
paths that can access mySet are addPerson and containsPerson , and each of these
acquires the lock on the PersonSet . All its state is guarded by its intrinsic lock, making
PersonSet thread-safe.
Search WWH ::




Custom Search