Java Concurrency Interview

Patterns and antipatterns question 158 of 180 mid

How do you make a class document its own thread safety?

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.

design documentation

Quiz yourself on Patterns and antipatterns Suggest a correction