1 4 package com.tc.util; 5 6 import sun.misc.Unsafe; 7 8 import com.tc.exception.TCRuntimeException; 9 import com.tc.object.TCObject; 10 import com.tc.object.bytecode.ManagerUtil; 11 12 import java.lang.reflect.Field ; 13 14 17 public class UnsafeUtil { 18 public final static String CLASS_SLASH = "com/tc/util/UnsafeUtil"; 19 public final static String CLASS_DESCRIPTION = "Lcom/tc/util/UnsafeUtil;"; 20 private final static Unsafe unsafe = findUnsafe(); 21 22 private UnsafeUtil() { 23 } 25 26 public static void updateDSOSharedField(Object obj, long fieldOffset, Object update) { 27 TCObject tcObject = ManagerUtil.lookupExistingOrNull(obj); 28 if (tcObject == null) { throw new NullPointerException ("Object is not a DSO shared object."); } 29 tcObject.objectFieldChangedByOffset(obj.getClass().getName(), fieldOffset, update, -1); 30 } 31 32 public static void setField(Object obj, Field field, Object value) { 33 long offset = unsafe.objectFieldOffset(field); 34 unsafe.putObject(obj, offset, value); 35 } 36 37 public static void monitorEnter(Object obj) { 38 unsafe.monitorEnter(obj); 39 } 40 41 public static void monitorExit(Object obj) { 42 unsafe.monitorExit(obj); 43 } 44 45 public static Unsafe getUnsafe() { 46 return unsafe; 47 } 48 49 private static Unsafe findUnsafe() { 50 Class uc = Unsafe.class; 51 Field [] fields = uc.getDeclaredFields(); 52 for (int i = 0; i < fields.length; i++) { 53 if (fields[i].getName().equals("theUnsafe")) { 54 fields[i].setAccessible(true); 55 try { 56 return (Unsafe) fields[i].get(uc); 57 } catch (IllegalArgumentException e) { 58 throw new TCRuntimeException(e); 59 } catch (IllegalAccessException e) { 60 throw new TCRuntimeException(e); 61 } 62 } 63 } 64 return null; 65 } 66 } 67 | Popular Tags |