Created
April 8, 2014 21:05
-
-
Save tixxit/10192336 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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(); | |
| } | |
| } |
Author
tixxit
commented
Apr 8, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment