Skip to content

Instantly share code, notes, and snippets.

@raphw
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raphw/6bc15c96a56546ba93bd to your computer and use it in GitHub Desktop.
Save raphw/6bc15c96a56546ba93bd to your computer and use it in GitHub Desktop.
Benchmark for calling synchronized code either by synchronizing a method or by synchronizing a block of code inside this method.
Benchmark Mode Samples Score Score error Units
b.SynchronizedTest.inner avgt 20 462,949 19,265 ns/op
b.SynchronizedTest.outer avgt 20 449,382 4,164 ns/op
# Run on x86, JDK 1.8.0_20
package benchmark;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@State(Scope.Group)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class SynchronizationBenchmark {
static class Outer {
int i;
synchronized int method() {
return i++;
}
}
static class Inner {
int j;
int method() {
synchronized (this) {
return j++;
}
}
}
private Outer outer;
private Inner inner;
@Setup
public void setUp() {
outer = new Outer();
inner = new Inner();
}
@Benchmark
@Group("outer")
@GroupThreads(10)
public int outerTest() {
return outer.method();
}
@Benchmark
@Group("inner")
@GroupThreads(10)
public int innerTest() {
return inner.method();
}
public static void main(String[] args) throws RunnerException {
new Runner(new OptionsBuilder()
.include(".*" + SynchronizationBenchmark.class.getSimpleName() + ".*")
.forks(1)
.build()).run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment