Minimize Your Lock Scopes
/** thread safe */
class Counter {
/** guarded by 'this' */
private long count;
void increment(long amount) {
synchronized (this) {
if (amount < 1) {
throw new IllegalArgumentException("Only increments!");
}
this.count += amount;
}
}
}
The synchronized block covers the whole method, including the check of amount. But that check only reads the parameter, which belongs to the calling thread alone. It doesn't touch any shared state, so there's no need to hold the lock while running it. Holding a lock longer than necessary makes other threads wait for nothing.
/** 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 validation now runs before the lock is acquired, and the synchronized block only covers the critical section: the update of count. Invalid calls fail without ever touching the lock, and valid calls hold it for the shortest possible time.
Here, the gain is tiny. But in real code, the part outside the lock can be expensive: parsing input, logging, or calling other services. The rule stays the same: lock exactly the code that accesses shared state, and nothing more.