Hide Your Locks
/** thread safe */
class Counter {
/** guarded by 'this' */
private long count;
void increment(long amount) {
if (amount < 1) {
throw new IllegalArgumentException("Only increments!");
}
synchronized (this) {
this.count += amount;
}
}
}
The counter locks on this. That's the default, but this is a public reference: anyone who holds a reference to the counter can also synchronize on it. Code elsewhere, which you neither know nor control, might hold that lock for a long time, or acquire it in a different order together with other locks, and cause unexpected waits or even a deadlock.
/** thread safe */
class Counter {
/** guarded by 'lock' */
private long count;
private final Object lock = new Object();
void increment(long amount) {
if (amount < 1) {
throw new IllegalArgumentException("Only increments!");
}
synchronized (this.lock) {
this.count += amount;
}
}
}
The counter now locks on a private final object that nobody outside the class can reach. So no other code can interfere with the counter's locking, and all reasoning about the lock stays within this one class. Declaring the lock final ensures that all threads always synchronize on the same object.
Don't forget to update the documentation: count is now guarded by lock, not by this.