Java多线程-10丨Unsafe

Posted by jiefang on November 1, 2019

Unsafe

前言

Unsafe是实现CAS的核心类,Java无法直接访问底层操作系统,而是通过本地(native)方法来访问。Unsafe类提供了硬件级别的原子操作。

特点

  • 私有的构造函数
  • 工厂方法getUnsafe()的调用器只能被Boot classloader加载,否则抛出SecurityException 异常
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
      private Unsafe() {
      }
    
      @CallerSensitive
      public static Unsafe getUnsafe() {
          Class var0 = Reflection.getCallerClass();
          if (!VM.isSystemDomainLoader(var0.getClassLoader())) {
              throw new SecurityException("Unsafe");
          } else {
              return theUnsafe;
          }
      }
    

    可以通过反射获取:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    public static Unsafe getUnsafe() {
     try {
             Field f = Unsafe.class.getDeclaredField("theUnsafe");
             f.setAccessible(true);
             return (Unsafe)f.get(null);
     } catch (Exception e) { 
         /* ... */
     }
    }
    

    方法

  • objectFieldOffset:能够获取到指定实例变量的在对象内存中的偏移量

    long offset = UNSAFE.objectFieldOffset(UnsafeTest.class.getDeclaredField(“state”));

  • compareAndSwapInt:通过比较并替换的机制,修改指定偏移量内存的值

    UNSAFE.compareAndSwapInt(unsafeTest, offset, 0, 1)

  • park():挂起某一线程
  • unpark():换线某一线程