1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| package chapter07;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
public class UnsafeUtils { private static Unsafe unsafe = null;
public static boolean compareAndSet(Object obj, String fieldName, Object expect, Object update) { try { init(); long valueOffset = computeOffset(obj, fieldName);
if (expect instanceof Integer) unsafe.compareAndSwapInt(obj, valueOffset, (Integer) expect, (Integer) update); else if (expect instanceof Long) unsafe.compareAndSwapLong(obj, valueOffset, (Long) expect, (Long) update); else unsafe.compareAndSwapObject(obj, valueOffset, expect, update); return true; } catch (Exception e) { } return false; }
private static void init() throws Exception { if (unsafe == null) { Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); unsafe = (Unsafe) field.get(null); } }
private static long computeOffset(Object obj, String fieldName) throws NoSuchFieldException { return unsafe.objectFieldOffset(obj.getClass().getDeclaredField(fieldName)); }
public static void main(String[] args) { Email email = new Email("zxf@123.com"); User user = new User("carl", 999, email);
Email email1 = new Email("hello.456");
System.out.println(user); UnsafeUtils.compareAndSet(user, "name", "carl", "hhh"); UnsafeUtils.compareAndSet(user, "age", 999, 99); UnsafeUtils.compareAndSet(user, "email", email, email1); System.out.println(user); } }
|