Last active
August 29, 2015 14:07
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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