Quote: In high concurrency you are still using Random to generate Random numbers

And the principle of ThreadLocalRandom class in the package is analyzed

1, instantiate sun.misc.Unsafe

Unsafe has a public method, getUnsafe(), whose return value is an instance of Unsafe. If direct call flip: the Exception in the thread “is the main” Java. Lang. SecurityException: Unsafe.

Here’s the caption: Although the class and all methods are public, use of this class is limited because only trusted code can obtain instances of it. Therefore, only code that Java deems safe can obtain Unsafe instances.

If you try to create an instance of the Unsafe class, it is not allowed for two reasons.

  • The Unsafe class constructor is private.
  • 2) Although it has a static getUnsafe() method, if you try to call unsafe.getunsafe (), you get a SecutiryException. This class is instantiated only by classes trusted by the JDK.

But there is always a workaround, and one simple way is to use reflection to instantiate

2. Test code:

private static Field fthreadLocalRandomSeed; private static final sun.misc.Unsafe UNSAFE; private static final long SEED; Static {try {// reflection gets threadLocalRandomSeed fthreadLocalRandomSeed = Thread.class.getDeclaredField("threadLocalRandomSeed"); fthreadLocalRandomSeed.setAccessible(true); / / get the unsafe object Field f = unsafe. Class. GetDeclaredField (" theUnsafe "); f.setAccessible(true); UNSAFE = (Unsafe) f.get(0); // Although it has a static getUnsafe() method, if you try to call unsafe.getunsafe (), you get a SecutiryException. This class is instantiated only by classes trusted by the JDK. // UNSAFE = sun.misc.Unsafe.getUnsafe(); Class<? > tk = Thread.class; SEED = unsafe. objectFieldOffset(tk.getDeclaredField("threadLocalRandomSeed")); } catch (Exception e) { throw new Error(e); Public static void byReflection() {try {long b = System.currentTimeMillis(); Thread t = Thread.currentThread(); fthreadLocalRandomSeed.set(t,0); for (long i=0; i < 100000000; i++ ) { fthreadLocalRandomSeed.set(t,(Long)fthreadLocalRandomSeed.get(t)+1); } long e = System.currentTimeMillis(); System.out.println("byReflection spend:" + (e-b) + "ms"); / / public static void byUnsafe() {/ / unaddressed, threadLocalRandomSeed; / / unaddressed, threadLocalRandomSeed; UNSAFE.putLong(Thread.currentThread(),SEED,0); long b = System.currentTimeMillis(); Thread t = Thread.currentThread(); for (long i = 0; i < 100000000; i++) { UNSAFE.putLong(t,SEED,UNSAFE.getLong(t,SEED)+1); } long e = System.currentTimeMillis(); System.out.println("byUnsafe spend:" + (e-b) + "ms"); } public static void main(String[] args) { try { byUnsafe(); byReflection(); System.out.println("==============="); } catch (Exception e) { e.printStackTrace(); }}Copy the code