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!");
}
lock.lock();
try {
this.count += amount;
} finally {
this.lock.unlock();
}
}
}
/** thread safe */
class Counter {
private final AtomicLong count = new AtomicLong();
void increment(long amount) {
if (amount < 1) {
throw new IllegalArgumentException("Only increments!");
}
this.count.addAndGet(amount);
}
}
while(true) {
if(!count.compareAndSet(old, new)) {
old = count.get();
new = old + 1;
}
}