I've created a program to check if @sun.misc.Contended
is in effect. The idea is that when @Contended
is in effect, the field offsets in annotated class will be larger.
I can see the expected difference in offsets on OpenJDK, if I specify the -XX:-RestrictContended
flag. I do not see any difference on OpenJ9 11 (jdk-11.0.1+13, Eclipse OpenJ9 VM-11.0.1) through.
The OpenJDK output is
readOnly: 12
writeOnly: 16
----
readOnly: 12
writeOnly: 144
The OpenJ9 output is
readOnly: 8
writeOnly: 12
----
readOnly: 8
writeOnly: 12
The program is
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class Main {
public static class Baseline {
int readOnly;
int writeOnly;
}
public static class Contended {
int readOnly;
@sun.misc.Contended
int writeOnly;
}
public static void main(String[] args) throws Exception {
Baseline b = new Baseline();
Contended s = new Contended();
printOffsets(b);
System.out.println("----");
printOffsets(s);
}
// https://blog.hazelcast.com/using-sun-misc-unsafe-in-java-9/
@SuppressWarnings("restriction")
private static Unsafe getUnsafe() throws NoSuchFieldException, IllegalAccessException {
Field singleoneInstanceField = Unsafe.class.getDeclaredField("theUnsafe");
singleoneInstanceField.setAccessible(true);
return (Unsafe) singleoneInstanceField.get(null);
}
// http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/
public static void printOffsets(Object o) throws Exception {
Unsafe u = getUnsafe();
Class c = o.getClass();
for (Field f : c.getDeclaredFields()) {
if ((f.getModifiers() & Modifier.STATIC) == 0) {
printOffset(u, f);
}
}
}
public static void printOffset(Unsafe u, Field f) {
long offset = u.objectFieldOffset(f);
System.out.println(f.getName() + ": " + offset);
}
}
At present, OpenJ9 supports
@Contended
at the class level only.