Created
June 18, 2016 21:42
-
-
Save guidomedina/d20381b55c89c641ccdb5e277edcd1b8 to your computer and use it in GitHub Desktop.
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
import sun.misc.Unsafe; | |
import java.lang.reflect.Field; | |
public class LazySetLong { | |
static final Unsafe unsafe; | |
static final long valueOffset; | |
volatile long o; | |
static { | |
try { | |
Field field = Unsafe.class.getDeclaredField("theUnsafe"); | |
field.setAccessible(true); | |
unsafe = (Unsafe) field.get(null); | |
valueOffset = unsafe.objectFieldOffset | |
(LazySetLong.class.getDeclaredField("o")); | |
} catch (Exception e) { | |
throw new AssertionError(e); | |
} | |
} | |
/** | |
* @param o It is only really useful where the field is volatile, and is thus expected to change unexpectedly. | |
* @throws NoSuchFieldException | |
*/ | |
public void lazySet(long o) throws NoSuchFieldException { | |
unsafe.putOrderedLong(this, valueOffset, o); | |
} | |
private long callPutOrderedLong(int times) throws NoSuchFieldException { | |
final long start = System.nanoTime(); | |
for (int i = 0; i < times; i++) { | |
lazySet(o + 1); | |
} | |
return System.nanoTime() - start; | |
} | |
private long setTheVolatileDirectly(int times) { | |
final long start = System.nanoTime(); | |
for (int i = 0; i < times; i++) { | |
o++; | |
} | |
return System.nanoTime() - start; | |
} | |
public static void main(String... args) throws NoSuchFieldException { | |
final LazySetLong that = new LazySetLong(); | |
for (int i = 0; i < 1000; i++) { | |
long time1 = that.callPutOrderedLong(100_000_000); | |
long time2 = that.setTheVolatileDirectly(100_000_000); | |
System.out.printf("Loop #%,d: callPutOrderedLong() took %.3fus and setting the volatile directly took %.3fus on average, ratio=%.3f%n", | |
i, time1 / 1e3, time2 / 1e3, (double) time1 / time2); | |
} | |
System.out.println("\nJust printing work so that it is not optimized out, work=" + that.o); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment