Skip to content

Commit

Permalink
Use sync instead of CAS-seeding with sun.misc.Unsafe in Random (#273)
Browse files Browse the repository at this point in the history
because it crashes HotSpot's C2 compiler...
  • Loading branch information
httpdigest committed Oct 26, 2020
1 parent 1f50824 commit 407eabd
Showing 1 changed file with 0 additions and 41 deletions.
41 changes: 0 additions & 41 deletions src/org/joml/Random.java
Original file line number Diff line number Diff line change
Expand Up @@ -123,56 +123,15 @@ final int nextInt(int n) {
//8020463840 is from "Case File n_221: Kabukicho"
private static long seedHalf = 8020463840L;

//#ifdef __HAS_UNSAFE__
private static final sun.misc.Unsafe UNSAFE = getUnsafeInstance();
private static final long seedHalf_offset = seedHalfOffset();

private static long seedHalfOffset() {
try {
return UNSAFE.staticFieldOffset(Random.class.getDeclaredField("seedHalf"));
} catch (Exception e) {
throw new UnsupportedOperationException();
}
}

private static sun.misc.Unsafe getUnsafeInstance() throws SecurityException {
java.lang.reflect.Field[] fields = sun.misc.Unsafe.class.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
java.lang.reflect.Field field = fields[i];
if (!field.getType().equals(sun.misc.Unsafe.class))
continue;
int modifiers = field.getModifiers();
if (!(java.lang.reflect.Modifier.isStatic(modifiers) && java.lang.reflect.Modifier.isFinal(modifiers)))
continue;
field.setAccessible(true);
try {
return (sun.misc.Unsafe) field.get(null);
} catch (IllegalAccessException e) {
/* Ignore */
}
break;
}
throw new UnsupportedOperationException();
}
//#endif

public static long newSeed() {
// 3512401965023503517 is from L'Ecuyer, "Tables of Linear Congruential Generators of
// Different Sizes and Good Lattice Structure", 1999
long oldSeedHalf, newSeedHalf;
//#ifdef __NHAS_UNSAFE__
synchronized (Random.class) {
//#else
do {
//#endif
oldSeedHalf = seedHalf;
newSeedHalf = oldSeedHalf * 3512401965023503517L;
//#ifdef __HAS_UNSAFE__
} while (!UNSAFE.compareAndSwapLong(Random.class, seedHalf_offset, oldSeedHalf, newSeedHalf));
//#else
seedHalf = newSeedHalf;
}
//#endif
return newSeedHalf;
}

Expand Down

0 comments on commit 407eabd

Please sign in to comment.