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;
}
}
}
- as a default,
thisis the reference of the lock - => everybody who has access to that object reference can interfere
/** 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;
}
}
}
- with a
privatelock object, the lock monitor stays local - update documentation!