package com.shadow.util;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j(topic = "e")
public class ShadowLock {
volatile int state=0;
static Unsafe unsafe;
private static long stateOffset;
/**
* 1、获取unsafe对象,这个对象的获取稍微有点复杂,目前不需要关心
* 2、通过unsafe对象得到state属性在当前对象当的偏移地址
*/
static {
try {
unsafe = getUnSafe();
stateOffset = unsafe.objectFieldOffset
(ShadowLock.class.getDeclaredField("state"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static Unsafe getUnSafe() throws NoSuchFieldException,
IllegalAccessException {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
return (Unsafe) theUnsafe.get(null);
}
public boolean compareAndSet(int expect,int x){
return unsafe.compareAndSwapInt(this, stateOffset, expect, x);
};
@SneakyThrows
public void lock(){
while(!compareAndSet(0,1)){
log.debug("lock fail");
TimeUnit.MILLISECONDS.sleep(300);
}
log.debug("lock success");
}
public void unlock(){
log.debug("unlock success");
state=0;
}
}