Skip to content

Instantly share code, notes, and snippets.

@ejain
Last active August 29, 2015 14:11
Show Gist options
  • Save ejain/5f5be1eaaf005dbb2db3 to your computer and use it in GitHub Desktop.
Save ejain/5f5be1eaaf005dbb2db3 to your computer and use it in GitHub Desktop.
A JMH microbenchmark to determine how a JVM is optimizing calls to synchronized methods.
Benchmark Mode Samples Score Error Units
b.SyncBenchmark.testField thrpt 10 288.380 ± 1.549 ops/s
b.SyncBenchmark.testFieldSync thrpt 10 23.297 ± 0.514 ops/s
b.SyncBenchmark.testLocal thrpt 10 859.547 ± 14.694 ops/s
b.SyncBenchmark.testLocalSync thrpt 10 859.833 ± 19.294 ops/s
package benchmark;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@State(Scope.Thread)
public class SyncBenchmark {
static class Counter {
int i;
int next() {
return i++;
}
synchronized int nextSync() {
return i++;
}
}
private Counter counter = new Counter();
@Benchmark
public void testLocal(Blackhole b) {
Counter counter = new Counter();
for (int i = 0; i < 1000000; ++i) {
b.consume(counter.next());
}
}
@Benchmark
public void testLocalSync(Blackhole b) {
Counter counter = new Counter();
for (int i = 0; i < 1000000; ++i) {
b.consume(counter.nextSync());
}
}
@Benchmark
public void testField(Blackhole b) {
for (int i = 0; i < 1000000; ++i) {
b.consume(counter.next());
}
}
@Benchmark
public void testFieldSync(Blackhole b) {
for (int i = 0; i < 1000000; ++i) {
b.consume(counter.nextSync());
}
}
public static void main(String... args) throws Exception {
Options opts = new OptionsBuilder()
.include(SyncBenchmark.class.getSimpleName())
.mode(Mode.Throughput)
.warmupIterations(10)
.measurementIterations(10)
.jvmArgs("-server")
.forks(1)
.build();
new Runner(opts).run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment