欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AQS 框架之 Unsafe 源码详解

程序员文章站 2022-03-18 16:28:03
■ 前言 之前 LockSupport 那篇已经叙述了是线程阻塞工具类,其底层由 Unsafe 实现,即 park(), unpark() 方法,获取指针偏移量,并操纵内存。本篇主要介绍 Unsafe 的源码,看看底层到底做了什么。 ■ Unsafe 综述 作用: Unsafe是个后门类,封装了一些 ......

■ 前言

  之前 LockSupport 那篇已经叙述了是线程阻塞工具类,其底层由 Unsafe 实现,即 park(), unpark() 方法,获取指针偏移量,并操纵内存。本篇主要介绍 Unsafe 的源码,看看底层到底做了什么。

 

■ Unsafe 综述

  • 作用: Unsafe是个后门类,封装了一些类似指针的操作,提供了一些可以直接操控内存和线程的底层操作
  • 使用: Unsafe被JDK广泛用于nio包和并发包中,但是不建议在生产环境使用,风险太大
  • 不安全: 不安全指的是指针的操作不安全(Java因此才把指针去掉),若指针指错位置或计算指针偏移量出错,结果不可想象,比如说覆盖了别人的内存,那可能就GG思密达了...
  • 补充1: 有机会开JVM番的话,笔者会从JVM源码角度重新解析Unsafe一些重要方法的实现
  • 补充2: 此番为 AQS 框架之综述 (赶制中) 的子番

 

■ Unsafe 数据结构

 1. 类定义

public final class Unsafe

   2. 构造器

//私有构造器 --单例模式
private Unsafe() {}

  3. 重要变量

private static final Unsafe theUnsafe;
public static final int INVALID_FIELD_OFFSET = -1;
public static final int ARRAY_BOOLEAN_BASE_OFFSET;
public static final int ARRAY_BYTE_BASE_OFFSET;
public static final int ARRAY_SHORT_BASE_OFFSET;
public static final int ARRAY_CHAR_BASE_OFFSET;
public static final int ARRAY_INT_BASE_OFFSET;
public static final int ARRAY_LONG_BASE_OFFSET;
public static final int ARRAY_FLOAT_BASE_OFFSET;
public static final int ARRAY_DOUBLE_BASE_OFFSET;
public static final int ARRAY_OBJECT_BASE_OFFSET;
public static final int ARRAY_BOOLEAN_INDEX_SCALE;
public static final int ARRAY_BYTE_INDEX_SCALE;
public static final int ARRAY_SHORT_INDEX_SCALE;
public static final int ARRAY_CHAR_INDEX_SCALE;
public static final int ARRAY_INT_INDEX_SCALE;
public static final int ARRAY_LONG_INDEX_SCALE;
public static final int ARRAY_FLOAT_INDEX_SCALE;
public static final int ARRAY_DOUBLE_INDEX_SCALE;
public static final int ARRAY_OBJECT_INDEX_SCALE;
public static final int ADDRESS_SIZE;
private static native void registerNatives();
static {
    registerNatives();
    Reflection.registerMethodsToFilter(Unsafe.class, new String[]{"getUnsafe"});
    theUnsafe = new Unsafe();//单例模式 -饿汉式
    ARRAY_BOOLEAN_BASE_OFFSET = theUnsafe.arrayBaseOffset(boolean[].class);
    ARRAY_BYTE_BASE_OFFSET = theUnsafe.arrayBaseOffset(byte[].class);
    ARRAY_SHORT_BASE_OFFSET = theUnsafe.arrayBaseOffset(short[].class);
    ARRAY_CHAR_BASE_OFFSET = theUnsafe.arrayBaseOffset(char[].class);
    ARRAY_INT_BASE_OFFSET = theUnsafe.arrayBaseOffset(int[].class);
    ARRAY_LONG_BASE_OFFSET = theUnsafe.arrayBaseOffset(long[].class);
    ARRAY_FLOAT_BASE_OFFSET = theUnsafe.arrayBaseOffset(float[].class);
    ARRAY_DOUBLE_BASE_OFFSET = theUnsafe.arrayBaseOffset(double[].class);
    ARRAY_OBJECT_BASE_OFFSET = theUnsafe.arrayBaseOffset(Object[].class);
    ARRAY_BOOLEAN_INDEX_SCALE = theUnsafe.arrayIndexScale(boolean[].class);
    ARRAY_BYTE_INDEX_SCALE = theUnsafe.arrayIndexScale(byte[].class);
    ARRAY_SHORT_INDEX_SCALE = theUnsafe.arrayIndexScale(short[].class);
    ARRAY_CHAR_INDEX_SCALE = theUnsafe.arrayIndexScale(char[].class);
    ARRAY_INT_INDEX_SCALE = theUnsafe.arrayIndexScale(int[].class);
    ARRAY_LONG_INDEX_SCALE = theUnsafe.arrayIndexScale(long[].class);
    ARRAY_FLOAT_INDEX_SCALE = theUnsafe.arrayIndexScale(float[].class);
    ARRAY_DOUBLE_INDEX_SCALE = theUnsafe.arrayIndexScale(double[].class);
    ARRAY_OBJECT_INDEX_SCALE = theUnsafe.arrayIndexScale(Object[].class);
    ADDRESS_SIZE = theUnsafe.addressSize();
}

  4. 重要方法

//获得给定对象内存偏移量的int值
public native int getInt(Object var1, long var2);
//设置给定对象内存偏移量的int值
public native void putInt(Object var1, long var2, int var4);
public native Object getObject(Object var1, long var2);
public native void putObject(Object var1, long var2, Object var4);
//....还有Boolean、Byte、Char、Short、Long、Float、Double的get\set....
//内存分配、释放
//分配内存
public native long allocateMemory(long var1);
//扩充内存
public native long reallocateMemory(long var1, long var3);
public native void setMemory(Object var1, long var2, long var4, byte var6);
public void setMemory(long var1, long var3, byte var5) {
    this.setMemory((Object)null, var1, var3, var5);
}
//拷贝内存
public native void copyMemory(Object var1, long var2, Object var4, long var5, long var7);
public void copyMemory(long var1, long var3, long var5) {
    this.copyMemory((Object)null, var1, (Object)null, var3, var5);
}
//释放内存
public native void freeMemory(long var1);
//获取字段在对象中的内存偏移量
public native long staticFieldOffset(Field var1);
public native long objectFieldOffset(Field var1);
public native Object staticFieldBase(Field var1);
public native void ensureClassInitialized(Class<?> var1);
//数组元素定位
//arrayBaseOffset 和 arrayIndexScale 搭配使用可以定位数组中每个元素在内存中的位置
//获取数组第一个元素的偏移地址
public native int arrayBaseOffset(Class<?> var1);
//获取数组的转换因子,也就是数组中元素的增量地址
public native int arrayIndexScale(Class<?> var1);
public native int addressSize();
public native int pageSize();
//类定义
public native Class<?> defineClass(String var1, byte[] var2, int var3, int var4, ClassLoader var5, ProtectionDomain var6);
public native Class<?> defineClass(String var1, byte[] var2, int var3, int var4);
public native Class<?> defineAnonymousClass(Class<?> var1, byte[] var2, Object[] var3);
//创建实例
public native Object allocateInstance(Class<?> var1) throws InstantiationException;
//Synchronized同步块的指令实现 1.8版的全部是@Deprecated
public native void monitorEnter(Object var1);
public native void monitorExit(Object var1);
public native boolean tryMonitorEnter(Object var1);
//异常抛出
public native void throwException(Throwable var1);
//CAS操作
/**
* 比较obj的offset处内存位置中的值和期望的值,如果相同则更新,此更新是不可中断的
* @param obj 需要更新的对象
* @param offset obj中整型field的偏移量
* @param expect 希望field中存在的值
* @param update 如果期望值expect与field的当前值相同,设置filed的值为这个新值
* @return 如果field的值被更改返回true
*/
public final native boolean compareAndSwapObject(Object obj, long offset, Object expect, Object update);
public final native boolean compareAndSwapInt(Object var1, long var2, int var4, int var5);
public final native boolean compareAndSwapLong(Object var1, long var2, long var4, long var6);
//获取给定对象的指定类型值,支持volatile load语义
public native Object getObjectVolatile(Object var1, long var2);
public native void putObjectVolatile(Object var1, long var2, Object var4);
public native int getIntVolatile(Object var1, long var2);
//设置给定对象的int值,支持volatile load语义
public native void putIntVolatile(Object var1, long var2, int var4);
//....还有Boolean、Byte、Char、Short、Long、Float、Double的volatile级别的get\put....
public native void putDoubleVolatile(Object var1, long var2, double var4);
public native void putOrderedObject(Object var1, long var2, Object var4);
public native void putOrderedInt(Object var1, long var2, int var4);
public native void putOrderedLong(Object var1, long var2, long var4);
//LockSupport类的原语支持-挂起和唤醒某个线程
public native void unpark(Object var1);
public native void park(boolean var1, long var2);
public native int getLoadAverage(double[] var1, int var2);
//提供线程安全的add和set操作
public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
    do {
        var5 = this.getIntVolatile(var1, var2);
    } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
    return var5;
}
public final int getAndSetInt(Object var1, long var2, int var4) {
    int var5;
    do {
        var5 = this.getIntVolatile(var1, var2);
    } while(!this.compareAndSwapInt(var1, var2, var5, var4));
    return var5;
}
//...还有Long和Object的线程安全的add和set操作...
//栅栏支持
public native void loadFence();
public native void storeFence();
public native void fullFence();

  5. 禁用的工厂方法

@CallerSensitive
public static Unsafe getUnsafe() {
    Class var0 = Reflection.getCallerClass();
    //该方法用于判断调用者的类加载器是否是系统核心加载器(即Bootstrap加载器)
    if(!VM.isSystemDomainLoader(var0.getClassLoader())) {
        throw new SecurityException("Unsafe");
    } else {
        return theUnsafe;
    }
}
  • 我们先显性调用该工厂方法查看一下调用结果
package concurrent;
import sun.misc.Unsafe;
public class UnsafeDemo {
    public static void main(String[] args) {
        Unsafe.getUnsafe();
    }
}
-------------------
//输出:
Exception in thread "main" java.lang.SecurityException: Unsafe
    at sun.misc.Unsafe.getUnsafe(Unsafe.java:90)
    at concurrent.UnsafeDemo.main(UnsafeDemo.java:7)
//分析:可以发现直接调用的话会直接抛出安全异常,原因是类加载器是AppClassLoader而并非是BootstrapLoader  

AQS 框架之 Unsafe 源码详解

 

  • 根据Java 类加载器的工作原理,应用程序的类由AppLoader加载,而系统核心类由BootstrapLoader加载
  • 当一个类的类加载器为null时,说明它是由BootstrapLoader加载的,即此类是系统核心类(比如rt.jar包中的类)
  • 当一个类无法被BootstrapLoader加载时,其类加载器通常为AppClassLoader,即是属于自定义类

 

■ Unsafe 反射获取

/** 
  * 我们可以通过反射机制获取Unsafe 的一个实例
  */
public static Unsafe getUnsafe(){
    try {
        //通过反射获取Unsafe的theUnsafe变量,即Unsafe实例对象
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        //注意field是static属性
        //参见:private static final Unsafe theUnsafe;
        return (Unsafe) f.get(null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}