class="java">import java.lang.reflect.Field; import sun.misc.Unsafe; /** * @author fhj * @date 2018年5月7日 下午4:16:21 * @version <b>1.0.0</b> */ public class CompareAndSwap { private static final Unsafe unsafe; private static final long fieldOffset; static { try { Class<?> clazz = User.class; unsafe = getUnsafe(); fieldOffset = unsafe.objectFieldOffset(clazz.getDeclaredField("age"));//获取User中age字段在内存中的偏移量 } catch (Exception ex) { throw new Error(ex); } } /** * boolean sun.misc.Unsafe.compareAndSwapInt(Object arg0, long arg1, int arg2, int arg3) * @param arg0-比较的对象 * @param arg1-需要修改的字段内存偏移量 * @param arg2-期待值(对比参考值) * @param arg3-修改的值 * 描述:argo对象中arg1偏移量指向的字段值如果等于arg2,则将arg1偏移量指向的字段值改为arg3,返回true * 否则不做任何操作,返回false */ public static void main(String[] args) { User user = new User(10); try { Boolean result; result = unsafe.compareAndSwapInt(user, fieldOffset, 10, 12); System.out.println(result);//true System.out.println(user.getAge());//12 result = unsafe.compareAndSwapInt(user, fieldOffset, 10, 14); System.out.println(result);//false System.out.println(user.getAge());//12 result = unsafe.compareAndSwapInt(user, fieldOffset, 12, 14); System.out.println(result);//true System.out.println(user.getAge());//14 } catch (Exception ex) { ex.printStackTrace(); } } /** * 通过代码反射获取Unsafe静态类 * 直接通过Unsafe.getUnsafe()获取会抛安全性异常 */ private static Unsafe getUnsafe() { try { Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); Unsafe unsafe = (Unsafe) field.get(null); return unsafe; } catch (Exception ex) { throw new Error(ex); } } static class User { private int age; User(int age) { this.age = age; } public int getAge() { return age; } } }
?
?
总结:因Unsafe类中的compareAndSwap方法是原子的,故可用来实现高性能的、无锁的数据结构?