Document for Concurrency
class Counter {
private long count;
synchronized void increment(long amount) {
if (amount < 1) {
throw new IllegalArgumentException("Only increments!");
}
this.count += amount;
}
}
The Counter is thread-safe now, but nothing tells its users. To find out, a reader has to inspect every method and check which fields are protected and how. That takes time, and with a larger class it's easy to get wrong. Someone adding a new method may not even notice that count must only be accessed while holding the lock.
/** thread safe */
class Counter {
/** guarded by 'this' */
private long count;
synchronized void increment(long amount) {
if (amount < 1) {
throw new IllegalArgumentException("Only increments!");
}
this.count += amount;
}
}
Two short comments make the design explicit. The class comment states that Counter is thread-safe, so callers know they can share an instance between threads. The field comment states which lock guards count, so maintainers know the rule they have to follow when they change the class.
These comments mirror the annotations @ThreadSafe and @GuardedBy from the book Java Concurrency in Practice. Useful categories for the class comment are thread-safe, immutable, conditionally thread-safe, and not thread-safe. Documenting a class as not thread-safe is just as valuable, because it tells users to protect it themselves.