/** 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;
}
}
}
this
is the reference of the lock
/** 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;
}
}
}
private
lock object, the lock monitor stays local