Skip to content

Instantly share code, notes, and snippets.

@guidomedina
Created June 18, 2016 21:42
Show Gist options
  • Save guidomedina/d20381b55c89c641ccdb5e277edcd1b8 to your computer and use it in GitHub Desktop.
Save guidomedina/d20381b55c89c641ccdb5e277edcd1b8 to your computer and use it in GitHub Desktop.
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);
}
}
@nitsanw
Copy link

nitsanw commented Jul 22, 2016

JMH please.

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