/** thread safe */
class Counter {
/** guarded by 'lock' */
private long count;
private final ReentrantLock lock = new ReentrantLock(true);
void increment(long amount) {
if (amount < 1) {
throw new IllegalArgumentException("Only increments!");
}
this.lock.lock();
try {
this.count += amount;
} finally {
this.lock.unlock();
}
}
}
- same behavior as
synchronized
- but also fair (see
true parameter in the constructor), real fcfs
- this comes at a slight cost
- close your resources with finally (link to other comparison)