Concurrent Programming Unsafe magic like magic

unsafe in this class is a class Jdk underlying mainly be used to operate the underlying memory, CAS, arrays, objects, memory operations, and some operations may span the underlying JVM. That is because the memory can operate, it will naturally cause some insecurity. All known unsafe.
unsafe is not new because its constructor is private, and the other if you want to use this method getUnsafe (), it is necessary to ensure that the class loader is the class loader to start,

private Unsafe() {
    }

    @CallerSensitive
    public static Unsafe getUnsafe() {
        Class var0 = Reflection.getCallerClass();
        if (!VM.isSystemDomainLoader(var0.getClassLoader())) {
            throw new SecurityException("Unsafe");
        } else {
            return theUnsafe;
        }
    }

Here Insert Picture Description
There obtaining unsafe Examples of this class is by reflection;

 public static Unsafe reflectGetUnsafe() {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            return (Unsafe) field.get(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

1. Memory operation

The method of operation is similar to malloc memory in C ++, you need to manually allocate memory and free memory.

 public static void main(String[] args) {

        Unsafe unsafe = UnsafeInstance.reflectGetUnsafe();

        long oneHundred = 1;
        byte size = 1;

        /*
         * 调用allocateMemory分配内存
         */
        long memoryAddress = unsafe.allocateMemory(size);

        /*
         * 将1写入到内存中
         */
        unsafe.putAddress(memoryAddress, oneHundred);

        /*
         * 内存中读取数据
         */
        long readValue = unsafe.getAddress(memoryAddress);

        System.out.println("value : " + readValue);
    }

CAS operation

cas concurrent programming operation of the core, it is also implemented in the unsafe class. Operation is based on the underlying CMPXCHG instruction.

  public final native boolean compareAndSwapObject(Object var1, long var2, Object var4, Object var5);

    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);

Found variables may be implemented to achieve an atomic operation according to the address offset.

public class AtomicStudentAgeUpdater {
    private String name ;
    private volatile int age;

    private static final Unsafe unsafe = UnsafeInstance.reflectGetUnsafe();
    private static final long valueOffset;

    static {
        try {
            valueOffset = unsafe.objectFieldOffset(AtomicStudentAgeUpdater.class.getDeclaredField("age"));
            System.out.println("valueOffset:--->"+valueOffset);
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    public void compareAndSwapAge(int old,int target){
        unsafe.compareAndSwapInt(this,valueOffset,old,target);
    }


    public AtomicStudentAgeUpdater(String name,int age){
        this.name = name;
        this.age = age;
    }

    public int getAge(){
        return this.age;
    }

    public static void main(String[] args) {
        AtomicStudentAgeUpdater updater = new AtomicStudentAgeUpdater("杨过",18);
        updater.compareAndSwapAge(18,56);

        System.out.println("真实的杨过年龄---"+updater.getAge());

    }
}
输出
valueOffset:--->12
真实的杨过年龄---56

Thread scheduling

  public native void unpark(Object var1);
  public native void park(boolean var1, long var2);
 /** @deprecated */
    @Deprecated
    public native void monitorEnter(Object var1);
    /** @deprecated */
    @Deprecated
    public native void monitorExit(Object var1);
    /** @deprecated */
    @Deprecated
    public native boolean tryMonitorEnter(Object var1);

park and unpark is thread suspend and resume operations.

Memory barrier

   public native void loadFence();
    public native void storeFence();
    public native void fullFence();

CPU and compiler random access memory heap sync point operation, the operation was carried out after after all read and write operations are executed prior to this point. Instructions to avoid reordering.

Released nine original articles · won praise 1 · views 648

Guess you like

Origin blog.csdn.net/weixin_42882491/article/details/104098055