VarHandle 简介

10月 30, 2023 |

VarHandle是用来代替Unsafe获取和修改对象的字段

private int state;
private int[] arr = new int[10];
private static int sVal;

private static VarHandle STATE ;
private static VarHandle S_VAL ;
private static VarHandle ARR ;
static {
	MethodHandles.Lookup l = MethodHandles.lookup();
	try {
		STATE = l.findVarHandle(VarHandleMain.class, "state", int.class);
		S_VAL = l.findStaticVarHandle(VarHandleMain.class, "sVal", int.class);
		ARR = MethodHandles.arrayElementVarHandle(new int[0].getClass());
	}catch (Exception e) {
		e.printStackTrace();
	}
}

public static void main(String[] args) {
	VarHandleMain obj = new VarHandleMain();
	STATE.compareAndSet(obj, 0, 100);
	log.info("state: {}", obj.state);
	S_VAL.compareAndSet( 0, 1024);
	log.info("sVal: {}", VarHandleMain.sVal);

	ARR.set(obj.arr, 0, 128);
	log.info("arr[0]: {}", obj.arr[0]);
}

Posted in: IT人生

Comments are closed.