我想知道在单线程环境中,与同步易失性增量相比,原子整数在多大程度上性能更好,并编写了这样一个JMH基准:
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class CounterBenchmark {
@State(Scope.Benchmark)
public static class ThreadState {
public final AtomicInteger atomicInteger = new AtomicInteger();
public final SynchronizedCounter synchronizedCounter = new SynchronizedCounter();
}
public static class SynchronizedCounter {
private volatile int counter = 0;
public synchronized int incrementAndGet() {
return counter++;
}
}
@Benchmark
public void atomicCounter(ThreadState state, Blackhole blackhole) {
blackhole.consume(state.atomicInteger.incrementAndGet());
}
@Benchmark
public void syncCounter(ThreadState state, Blackhole blackhole) {
blackhole.consume(state.synchronizedCounter.incrementAndGet());
}
public static void main(String... args) throws Exception {
Options options = new OptionsBuilder()
.include(CounterBenchmark.class.getSimpleName())
.forks(1)
.threads(1)
.warmupTime(TimeValue.seconds(1))
.warmupIterations(5)
.measurementTime(TimeValue.seconds(1))
.measurementIterations(5)
.mode(Mode.Throughput)
.build();
new Runner(options).run();
}
}
并得到了这样的输出:
Benchmark Mode Cnt Score Error Units MySerializationBenchmark.atomicCounter thrpt 5 145125.272 ± 2064.673 ops/ms MySerializationBenchmark.syncCounter thrpt 5 105763.168 ± 1794.680 ops/ms
个
而且结果似乎很快.每1ms 145k次操作(145kk/秒),用于同步的100kk次. 是我做错了什么,还是这是真正的表演. `
我在谷歌上搜索了一些东西,比如"常见的Java延迟数字"等等,但我决定自己做基准测试