Java Reference
In-Depth Information
why would you want to? Encapsulating data within objects makes it easier to pre-
serve their invariants; encapsulating synchronization within objects makes it easier
to comply with their synchronization policy.
•
Guard each mutable variable with a lock.
•
Guard all variables in an invariant with the same lock.
•
Hold locks for the duration of compound actions.
•
Aprogramthataccessesamutablevariablefrommultiplethreadswithoutsynchron-
ization is a broken program.
•
Don't rely on clever reasoning about why you don't need to synchronize.
•
Includethreadsafetyinthedesignprocess—orexplicitlydocumentthatyourclassis
not thread-safe.
•
Document your synchronization policy.