/** * A collection of methods for performing low-level, unsafe operations. * Although the class and all methods are public, use of this class is * limited because only trusted code can obtain instances of it. * * @author John R. Rose * @see #getUnsafe */ public final class Unsafe {
/** * Sets all bytes in a given block of memory to a copy of another * block. * * <p>This method determines each block's base address by means of two parameters, * and so it provides (in effect) a <em>double-register</em> addressing mode, * as discussed in {@link #getInt(Object,long)}. When the object reference is null, * the offset supplies an absolute base address. * * <p>The transfers are in coherent (atomic) units of a size determined * by the address and length parameters. If the effective addresses and * length are all even modulo 8, the transfer takes place in 'long' units. * If the effective addresses and length are (resp.) even modulo 4 or 2, * the transfer takes place in units of 'int' or 'short'. * * @since 1.7 */ public native void copyMemory(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
public static void main(String[] args) throws NoSuchFieldException { User user = new User(); // 使用unsafe的api获取字段的偏移量,需要通过反射来获取字段的Field对象 Field age = User.class.getDeclaredField("age"); long ageAddr = UNSAFE.objectFieldOffset(age); // 设置时把对象的偏移量传入 UNSAFE.putInt(user, ageAddr, 10); // 取出时也是通过偏移量 UNSAFE.getInt(user, ageAddr); }
/** * Atomically update Java variable to <tt>x</tt> if it is currently * holding <tt>expected</tt>. * @return <tt>true</tt> if successful */ public final native boolean compareAndSwapObject(Object o, long offset, Object expected, Object x);
比较并替换,设置之前比较数据是否是和预期是一致的,设置之后比较数据是否和设置的数据是一致的。
这种方式能在无锁的情况下进行并发操作,性能会非常高。
类似的还有比较并递增,但是它的实现会有些区别:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/** * Atomically adds the given value to the current value of a field * or array element within the given object <code>o</code> * at the given <code>offset</code>. * * @param o object/array to update the field/element in * @param offset field/element offset * @param delta the value to add * @return the previous value * @since 1.8 */ public final int getAndAddInt(Object o, long offset, int delta) { int v; do { v = getIntVolatile(o, offset); } while (!compareAndSwapInt(o, offset, v, v + delta)); return v; }