5. 5
Simple Counter
class SimpleCounter implements Counter {
private long value = 0;
public long get() {
return value;
}
public void increment() {
value++;
}
}
6. 6
Volatile Counter
class VolatileCounter implements Counter {
volatile long value = 0;
public long get() {
return value;
}
public void increment() {
value++;
}
}
7. 7
Volatile Counter
class VolatileCounter implements Counter {
volatile long value = 0;
public long get() {
return value;
}
public void increment() {
long oldValue = value; // read
long newValue = oldValue + 1; // modify
value = newValue; // write
}
}
8. 8
class SynchronizedCounter implements Counter {
volatile long value = 0;
public synchronized long get() {
return value;
}
public synchronized void increment() {
value++;
}
}
Synchronized Counter
21. 21
Как устроен типичный Core i7
CPU 4
CPU 0
CPU 5
CPU 1
CPU 6
CPU 2
CPU 7
CPU 3
L1 cache
L2 cache
L1 cache L1 cache L1 cache
L2 cache L2 cache L2 cache
L3 cache
25. 25
CAS Counter
public class CasLoopCounter implements Counter {
private AtomicLong value = new AtomicLong();
public long get() {
return value.get();
}
public void increment() {
for (;;) {
long oldValue = value.get();
long newValue = oldValue + 1;
if (value.compareAndSet(oldValue, newValue))
return;
}
}
}
28. 28
Get-and-Add Counter
public class CasLoopCounter implements Counter {
private AtomicLong value = new AtomicLong();
public long get() {
return value.get();
}
public void increment() {
value.getAndAdd(1);
}
}
43. 43
StampedLock Counter
public class StampedLockCounter implements Counter {
private long value = 0;
private StampedLock lock = new StampedLock();
public long get() { ... }
public void add() {
long stamp = lock.writeLock();
try {
value++;
} finally{
lock.unlock(stamp);
}
}
}
45. 45
Long Adder Counter
public class LongAdderCounter implements Counter {
private LongAdder value = new LongAdder();
public long get() {
return value.longValue();
}
public void increment() {
value.add(1);
}
}