Use Fair Locks
/** 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;
}
}
}
The intrinsic lock behind synchronized makes no promise about the order in which waiting threads get the lock. When it's released, any waiting thread may get it next, even one that just arrived. Under high contention, an unlucky thread can wait much longer than others, in theory indefinitely.
/** 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();
}
}
}
A ReentrantLock behaves like synchronized, but offers more options. Passing true to the constructor makes it fair: waiting threads get the lock in the order they asked for it, first come, first served. No thread starves anymore.
Fairness comes at a cost, since handing over the lock in strict order reduces throughput. And the lock is no longer released automatically: you have to call unlock() yourself, in a finally block, so that the lock is released even when an exception occurs. Use a fair lock only when the order actually matters.