Java Reference
In-Depth Information
4.1.1. Gathering Synchronization Requirements
Making a class thread-safe means ensuring that its invariants hold under concurrent access;
this requires reasoning about its state. Objects and variables have a state space : the range of
possible states they can take on. The smaller this state space, the easier it is to reason about.
By using final fields wherever practical, you make it simpler to analyze the possible states an
object can be in. (In the extreme case, immutable objects can only be in a single state.)
Many classes have invariants that identify certain states as valid or invalid . The value field
in Counter is a long . The state space of a long ranges from Long.MIN_VALUE to
Long.MAX_VALUE , but Counter places constraints on value ; negative values are not
allowed.
Similarly, operations may have postconditions that identify certain state transitions as inval-
id. If the current state of a Counter is 17, the only valid next state is 18. When the next
state is derived from the current state, the operation is necessarily a compound action. Not all
operations impose state transition constraints; when updating a variable that holds the current
temperature, its previous state does not affect the computation.
Constraints placed on states or state transitions by invariants and postconditions create ad-
ditional synchronization or encapsulation requirements. If certain states are invalid, then the
underlying state variables must be encapsulated, otherwise client code could put the object
into an invalid state. If an operation has invalid state transitions, it must be made atomic. On
Search WWH ::




Custom Search