
public class VolatileTest {
private static final int THREAD_COUNT = 20;
private static volatile int race = ;
public static void increase() {
race++;
}
public static void main(String[] args) {
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = ; i < THREAD_COUNT; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
for (int i = ; i < 1000; i++) {
increase();
}
}
});
threads[i].start();
}
//等所有累加线程都结束
while (Thread.activeCount() > 1) {
Thread.yield();
}
System.out.println("race: " + race);
}
}
public class AtomicLongTest {
private static final int THREAD_COUNT = 20;
private static volatile AtomicLong race = new AtomicLong();
public static void increase() {
race.getAndIncrement();
}
public static void main(String[] args) {
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = ; i < THREAD_COUNT; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
for (int i = ; i < 1000; i++) {
increase();
}
}
});
threads[i].start();
}
//等所有累加线程都结束
while (Thread.activeCount() > 1) {
Thread.yield();
}
System.out.println("race: " + race);
}
}运算后得到了预期结果:20000。
public class LongAdderTest {
private static final int THREAD_COUNT = 20;
//默认初始化为0值
private static volatile LongAdder race = new LongAdder();
public static void increase() {
race.increment();
}
public static void main(String[] args) {
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = ; i < THREAD_COUNT; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
for (int i = ; i < 1000; i++) {
increase();
}
}
});
threads[i].start();
}
while (Thread.activeCount() > 1) {
Thread.yield();
}
System.out.println("race: " + race);
}
}结果也是预期的20000。
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class PerformaceTest {
private static AtomicLong atomicLong = new AtomicLong();
private static LongAdder longAdder = new LongAdder();
@Benchmark
@Threads(10)
public void atomicLongAdd() {
atomicLong.getAndIncrement();
}
@Benchmark
@Threads(10)
public void longAdderAdd() {
longAdder.increment();
}
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder().include(PerformaceTest.class.getSimpleName()).build();
new Runner(options).run();
}
}说明:
Benchmark Mode Cnt Score Error Units
PerformaceTest.atomicLongAdd thrpt 200 153824.699 ± 137.947 ops/ms
PerformaceTest.longAdderAdd thrpt 200 124087.220 ± 81.015 ops/ms线程数为5:
PerformaceTest.atomicLongAdd thrpt 200 56392.136 ± 1165.361 ops/ms
PerformaceTest.longAdderAdd thrpt 200 605501.870 ± 4140.190 ops/ms线程数为10:
Benchmark Mode Cnt Score Error Units
PerformaceTest.atomicLongAdd thrpt 200 53286.334 ± 957.765 ops/ms
PerformaceTest.longAdderAdd thrpt 200 713884.602 ± 3950.884 ops/ms从测试结果来看,当线程数为5时,LongAdder的性能已经优于AtomicLong。
//AtomicLong#getAndIncrement
public final long getAndIncrement() {
return unsafe.getAndAddLong(this, valueOffset, 1L);
}
//Unsafe#getAndAddLong
public final long getAndAddLong(Object var1, long var2, long var4) {
long var6;
do {
var6 = this.getLongVolatile(var1, var2);
} while(!this.compareAndSwapLong(var1, var2, var6, var6 + var4));
return var6;
}
public void increment() {
add(1L);
}
public void add(long x) {
Cell[] as; long b, v; int m; Cell a;
if ((as = cells) != null || !casBase(b = base, b + x)) {
boolean uncontended = true;
if (as == null || (m = as.length - 1) < ||
(a = as[getProbe() & m]) == null ||
!(uncontended = a.cas(v = a.value, v + x)))
longAccumulate(x, null, uncontended);
}
}
final void longAccumulate(long x, LongBinaryOperator fn,
boolean wasUncontended) {
int h;
if ((h = getProbe()) == ) {
ThreadLocalRandom.current(); // force initialization
h = getProbe();
wasUncontended = true;
}
boolean collide = false; // True if last slot nonempty
for (;;) {
Cell[] as; Cell a; int n; long v;
if ((as = cells) != null && (n = as.length) > ) {
if ((a = as[(n - 1) & h]) == null) {
if (cellsBusy == ) { // Try to attach new Cell
Cell r = new Cell(x); // Optimistically create
if (cellsBusy == && casCellsBusy()) {
boolean created = false;
try { // Recheck under lock
Cell[] rs; int m, j;
if ((rs = cells) != null &&
(m = rs.length) > &&
rs[j = (m - 1) & h] == null) {
rs[j] = r;
created = true;
}
} finally {
cellsBusy = ;
}
if (created)
break;
continue; // Slot is now non-empty
}
}
collide = false;
}
else if (!wasUncontended) // CAS already known to fail
wasUncontended = true; // Continue after rehash
else if (a.cas(v = a.value, ((fn == null) ? v + x :
fn.applyAsLong(v, x))))
break;
else if (n >= NCPU || cells != as)
collide = false; // At max size or stale
else if (!collide)
collide = true;
else if (cellsBusy == && casCellsBusy()) {
try {
if (cells == as) { // Expand table unless stale
Cell[] rs = new Cell[n << 1];
for (int i = ; i < n; ++i)
rs[i] = as[i];
cells = rs;
}
} finally {
cellsBusy = ;
}
collide = false;
continue; // Retry with expanded table
}
h = advanceProbe(h);
}
else if (cellsBusy == && cells == as && casCellsBusy()) {
boolean init = false;
try { // Initialize table
if (cells == as) {
Cell[] rs = new Cell[2];
rs[h & 1] = new Cell(x);
cells = rs;
init = true;
}
} finally {
cellsBusy = ;
}
if (init)
break;
}
else if (casBase(v = base, ((fn == null) ? v + x :
fn.applyAsLong(v, x))))
break; // Fall back on using base
}
}代码很长,可以结合图片理解:

public long sum() {
Cell[] as = cells; Cell a;
long sum = base;
if (as != null) {
for (int i = ; i < as.length; ++i) {
if ((a = as[i]) != null)
sum += a.value;
}
}
return sum;
}

-End-
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69991250/viewspace-3126975/ ,如需转载,请注明出处,否则将追究法律责任。