Make Locks Explicit
/** thread safe */
class Counter {
/** guarded by 'this' */
private long count;
synchronized void increment(long amount) {
if (amount < 1) {
throw new IllegalArgumentException("Only increments!");
}
this.count += amount;
}
}
synchronizedin the method may be short, but readers who aren't that familiar withsynchronizedmay get the wrong impression- especially if the documentation is missing...
/** 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;
}
}
}
- You should make the scope of the
synchronizedblock explicit