Skip to content

Instantly share code, notes, and snippets.

@tixxit
Created April 8, 2014 21:05
Show Gist options
  • Select an option

  • Save tixxit/10192336 to your computer and use it in GitHub Desktop.

Select an option

Save tixxit/10192336 to your computer and use it in GitHub Desktop.
package net.tixxit.snippets;
import org.openjdk.jmh.annotations.GenerateMicroBenchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
public class VolatileVsThreadLocalBenchmark {
@State(Scope.Benchmark)
public static class ThreadLocalState {
ThreadLocal<Integer> tl = new ThreadLocal<Integer>();
public Integer inc() {
Integer x = tl.get();
if (x == null) x = 0;
tl.set(x + 1);
return x;
}
}
@State(Scope.Thread)
public static class VolatileState {
volatile Integer vo = null;
public Integer inc() {
Integer x = vo;
if (x == null) x = 0;
vo = x + 1;
return x;
}
}
@GenerateMicroBenchmark
public int testThreadLocal(ThreadLocalState state) {
return state.inc();
}
@GenerateMicroBenchmark
public int testVolatile(VolatileState state) {
return state.inc();
}
}
@tixxit
Copy link
Copy Markdown
Author

tixxit commented Apr 8, 2014

Benchmark                                                Mode   Samples         Mean   Mean error    Units
n.t.s.VolatileVsThreadLocalBenchmark.testThreadLocal    thrpt         5   153081.466    25534.485   ops/ms
n.t.s.VolatileVsThreadLocalBenchmark.testVolatile       thrpt         5    61799.546     6802.259   ops/ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment