一,简介
Unsafe可以用于获取成员字段在类实例中的偏移量,直接操作变量在主内存中的值等操作。
1,获取unsafe.objectFieldOffset(Field f)成员变量地址偏移量。
public class AtomicInteger extends Number implements java.io.Serializable { private static final long serialVersionUID = 6214790243416807050L; // setup to use Unsafe.compareAndSwapInt for updates private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long valueOffset; static { try { valueOffset = unsafe.objectFieldOffset (AtomicInteger.class.getDeclaredField("value"));//获取该字段的偏移量 } catch (Exception ex) { throw new Error(ex); } } private volatile int value;//成员字段 /** * Creates a new AtomicInteger with the given initial value. * * @param initialValue the initial value */ public AtomicInteger(int initialValue) { value = initialValue; } }2,根据字段偏移量获取实例中此字段的值。
long offset = unsafe.objectFieldOffset(User.class.getDeclaredField("age")); Object obj = unsafe.getInt(this, offset);//获取int型值,getObject(),getLong()等 System.out.println(obj);3,CAS算法支持
public class AtomicBoolean implements java.io.Serializable { /** * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * * @param expect the expected value * @param update the new value * @return true if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(boolean expect, boolean update) { int e = expect ? 1 : 0; int u = update ? 1 : 0; return unsafe.compareAndSwapInt(this, valueOffset, e, u);//如果主内存中的值是期望 //的e则替换成u并返回true,否则返回false。 } }4,获取Unsafe实例
/**import sun.misc.Unsafe;导入此包 * 反射获取该实例,还绕开了安全管理器的限制 */ private static Unsafe getUnsafeInstance() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafeInstance.setAccessible(true); return (Unsafe) theUnsafeInstance.get(Unsafe.class);//返回指定对象上此Field字段表示的值 }
二,总结
Unsafe提供了直接操作主内存(堆内存)的方法,但sun公司是通过安全管理器限制了直接获取Unsafe的,毕竟应用层直接操作主内存是不安全的,当然也是不允许的。更多关于Unsafe类的应用,请阅读JDK中原子类的实现。
已有 0人发表留言,猛击->> 这里<<-参与讨论
ITeye推荐