Unsafe(转载)
1.报错
Unsafe unsafe = Unsafe.getUnsafe();
java.lang.SecurityException: Unsafe
at sun.misc.Unsafe.getUnsafe(Unsafe.java:68)
at Person.main(Person.java:37)
这样则正确
Unsafe unsafe =null;
try{
Class<?> clazz = Unsafe.class;
Field f;
f = clazz.getDeclaredField("theUnsafe");
f.setAccessible(true);
unsafe = (Unsafe) f.get(clazz);
} catch (IllegalAccessException e) {
e.printStackTrace();
}catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2.API介绍:
boolean compareAndSwapInt(Object obj,long fieldoffset, int expect, int update);
修改 obj对象的(fieldoffset)Int 属性值,若属性值为expect,则修改为 update ,返回true,若属性值不为expect则不修改,返回false
boolean compareAndSwapObject(Object obj,long Fieldoffset, Object expect, Object update);
修改 obj对象的(fieldoffset)属性值,若属性值为expect,则修改为 update ,返回true,若属性值不为expect则不修改,返回false
long objectFieldOffset (Field field);
得到 filed在对象中的偏移
void park(boolean flag, long time);
使当前线程等待
void unpark(Thread thread)
使当前线程停止等待
Object getObject(Object obj,long fieldoffset);
得到 obj 的 偏移为fieldoffset 的属性
int getInt(Object obj,long fieldoffset);
得到 obj 的 偏移为fieldoffset 的int属性
Unsafe unsafe = Unsafe.getUnsafe();
java.lang.SecurityException: Unsafe
at sun.misc.Unsafe.getUnsafe(Unsafe.java:68)
at Person.main(Person.java:37)
这样则正确
Unsafe unsafe =null;
try{
Class<?> clazz = Unsafe.class;
Field f;
f = clazz.getDeclaredField("theUnsafe");
f.setAccessible(true);
unsafe = (Unsafe) f.get(clazz);
} catch (IllegalAccessException e) {
e.printStackTrace();
}catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2.API介绍:
boolean compareAndSwapInt(Object obj,long fieldoffset, int expect, int update);
修改 obj对象的(fieldoffset)Int 属性值,若属性值为expect,则修改为 update ,返回true,若属性值不为expect则不修改,返回false
boolean compareAndSwapObject(Object obj,long Fieldoffset, Object expect, Object update);
修改 obj对象的(fieldoffset)属性值,若属性值为expect,则修改为 update ,返回true,若属性值不为expect则不修改,返回false
long objectFieldOffset (Field field);
得到 filed在对象中的偏移
void park(boolean flag, long time);
使当前线程等待
void unpark(Thread thread)
使当前线程停止等待
Object getObject(Object obj,long fieldoffset);
得到 obj 的 偏移为fieldoffset 的属性
int getInt(Object obj,long fieldoffset);
得到 obj 的 偏移为fieldoffset 的int属性