Patterns and antipatterns question 158 of 180 mid
How do you make a class document its own thread safety?
- By naming it
SafeFoo - Correct: By stating the policy in the javadoc and marking fields with
@GuardedBy, so the reader knows which lock covers what - By making every method synchronized
- Thread safety cannot be documented
A class is thread safe, conditionally thread safe, or not, and the reader cannot tell by looking. State
it in one sentence at the top of the javadoc: "Thread safe. All mutable state is guarded by lock."
Or: "Not thread safe. Confine instances to one thread."
@GuardedBy("lock") on a field names the invariant precisely, is checkable by static analysis tools
(SpotBugs, ErrorProne), and survives the refactoring that a comment would not. For conditionally
thread-safe classes, say which compound sequences the caller must lock, and which lock to use.
This is not paperwork: an undocumented thread safety policy is how correct code becomes incorrect two maintainers later.
Quiz yourself on Patterns and antipatterns Suggest a correction