Java Reference
In-Depth Information
NumberRange could be made thread-safe by using locking to maintain its invariants, such
as guarding lower and upper with a common lock. It must also avoid publishing lower
and upper to prevent clients from subverting its invariants.
If a class has compound actions, as NumberRange does, delegation alone is again not a
suitable approach for thread safety. In these cases, the class must provide its own locking to
ensure that compound actions are atomic, unless the entire compound action can also be del-
egated to the underlying state variables.
If a class is composed of multiple independent thread-safe state variables and has no opera-
tions that have any invalid state transitions, then it can delegate thread safety to the underly-
ing state variables.
The problem that prevented NumberRange from being thread-safe even though its state
components were thread-safe is very similar to one of the rules about volatile variables de-
scribed in Section 3.1.4 : a variable is suitable for being declared volatile only if it does
not participate in invariants involving other state variables.
4.3.4. Publishing Underlying State Variables
When you delegate thread safety to an object's underlying state variables, under what condi-
tions can you publish those variables so that other classes can modify them as well? Again,
the answer depends on what invariants your class imposes on those variables. While the un-
derlying value field in Counter could take on any integer value, Counter constrains it
to take on only positive values, and the increment operation constrains the set of valid next
states given any current state. If you were to make the value field public, clients could
change it to an invalid value, so publishing it would render the class incorrect. On the other
hand, if a variable represents the current temperature or the ID of the last user to log on, then
having another class modify this value at any time probably would not violate any invariants,
so publishing this variable might be acceptable. (It still may not be a good idea, since publish-
ing mutable variables constrains future development and opportunities for subclassing, but it
would not necessarily render the class not thread-safe.)
If a state variable is thread-safe, does not participate in any invariants that constrain its value,
and has no prohibited state transitions for any of its operations, then it can safely be pub-
lished.
Search WWH ::




Custom Search