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;
}
}
}
- guard doesn't access shared state
- scope of
synchronizedis too large
/** 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;
}
}
}
- reduce the lock to the critical section!