Java Reference
In-Depth Information
able to eliminate the locking that would otherwise be required when shared a
Date
across
threads. Suppose you want to maintain a
Map
storing the last login time of each user:
If the
Date
values are not modified after they are placed in the
Map
, then the synchronization
in the
synchronizedMap
implementation is sufficient to publish the
Date
values safely,
and no additional synchronization is needed when accessing them.
3.5.5. Mutable Objects
If an object may be modified after construction, safe publication ensures only the visibility
of the as-published state. Synchronization must be used not only to publish a mutable object,
but also every time the object is accessed to ensure visibility of subsequent modifications.
To share mutable objects safely, they must be safely published
and
be either thread-safe or
guarded by a lock.
The publication requirements for an object depend on its mutability:
•
Immutable objects
can be published through any mechanism;
•
Effectively immutable objects
must be safely published;
•
Mutable objects
must be safely published, and must be either threadsafe or guarded
by a lock.
3.5.6. Sharing Objects Safely
Whenever you acquire a reference to an object, you should know what you are allowed to do
with it. Do you need to acquire a lock before using it? Are you allowed to modify its state,
or only to read it? Many concurrency errors stem from failing to understand these “rules of
engagement” for a shared object. When you publish an object, you should document how the
object can be accessed.
The most useful policies for using and sharing objects in a concurrent program are: