Skip to content

Instantly share code, notes, and snippets.

@gusakovgiorgi
Created February 23, 2020 20:59
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 gusakovgiorgi/90202ff2edc2e842026678feb998bffb to your computer and use it in GitHub Desktop.
Save gusakovgiorgi/90202ff2edc2e842026678feb998bffb to your computer and use it in GitHub Desktop.
Java class for comparing synchronized and non-synchronized methods with JMH
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import java.util.concurrent.TimeUnit;
public class SyncNotSyncBenchmark {
@State(Scope.Thread)
public static class MyState {
public int loopSize = 100;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void nonSyncTest(MyState myState, Blackhole blackhole) {
for (int i = 0; i < myState.loopSize; i++) {
blackhole.consume(result(i));
}
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void syncTes(MyState myState, Blackhole blackhole) {
for (int i = 0; i < myState.loopSize; i++) {
blackhole.consume(syncResult(i));
}
}
public static synchronized int syncResult(int i) {
int a = i;
int b = a * 2;
int sum = (int) (a * b * 10 / 10.0);
return sum;
}
public static int result(int i) {
int a = i;
int b = a * 2;
int sum = (int) (a * b * 10 / 10.0);
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment