package org.ehcache.impl.internal.concurrent;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.security.PrivilegedExceptionAction;
import java.util.concurrent.ThreadLocalRandom;
class ThreadLocalRandomUtil {
static final Unsafe UNSAFE = getSMU();
private static final long PROBE;
static {
try {
Class<?> tk = Thread.class;
PROBE = UNSAFE.objectFieldOffset
(tk.getDeclaredField("threadLocalRandomProbe"));
} catch (Exception e) {
throw new Error(e);
}
}
static Unsafe getSMU() {
try {
return sun.misc.Unsafe.getUnsafe();
} catch (SecurityException tryReflectionInstead) {
}
try {
return java.security.AccessController.doPrivileged
((PrivilegedExceptionAction<Unsafe>) () -> {
Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
for (Field f : k.getDeclaredFields()) {
f.setAccessible(true);
Object x = f.get(null);
if (k.isInstance(x))
return k.cast(x);
}
throw new NoSuchFieldError("the Unsafe");
});
} catch (java.security.PrivilegedActionException e) {
throw new RuntimeException("Could not initialize intrinsics", e.getCause());
}
}
static final int getProbe() {
return UNSAFE.getInt(Thread.currentThread(), PROBE);
}
static final int advanceProbe(int probe) {
probe ^= probe << 13;
probe ^= probe >>> 17;
probe ^= probe << 5;
UNSAFE.putInt(Thread.currentThread(), PROBE, probe);
return probe;
}
static final void localInit() {
ThreadLocalRandom.current();
}
static String mapEntryToString(Object key, Object val) {
final String k, v;
final int klen, vlen;
final char[] chars =
new char[(klen = (k = objectToString(key)).length()) +
(vlen = (v = objectToString(val)).length()) + 1];
k.getChars(0, klen, chars, 0);
chars[klen] = '=';
v.getChars(0, vlen, chars, klen + 1);
return new String(chars);
}
private static String objectToString(Object x) {
String s;
return (x == null || (s = x.toString()) == null) ? "null" : s;
}
}