01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.util;
05:
06: import sun.misc.Unsafe;
07:
08: import com.tc.exception.TCRuntimeException;
09: import com.tc.object.TCObject;
10: import com.tc.object.bytecode.ManagerUtil;
11:
12: import java.lang.reflect.Field;
13:
14: /**
15: * A wrapper for unsafe usage in class like Atomic Variables, ReentrantLock, etc.
16: */
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: // Disallow any object to be instantiated.
24: }
25:
26: public static void updateDSOSharedField(Object obj,
27: long fieldOffset, Object update) {
28: TCObject tcObject = ManagerUtil.lookupExistingOrNull(obj);
29: if (tcObject == null) {
30: throw new NullPointerException(
31: "Object is not a DSO shared object.");
32: }
33: tcObject.objectFieldChangedByOffset(obj.getClass().getName(),
34: fieldOffset, update, -1);
35: }
36:
37: public static void setField(Object obj, Field field, Object value) {
38: long offset = unsafe.objectFieldOffset(field);
39: unsafe.putObject(obj, offset, value);
40: }
41:
42: public static void monitorEnter(Object obj) {
43: unsafe.monitorEnter(obj);
44: }
45:
46: public static void monitorExit(Object obj) {
47: unsafe.monitorExit(obj);
48: }
49:
50: public static Unsafe getUnsafe() {
51: return unsafe;
52: }
53:
54: private static Unsafe findUnsafe() {
55: Class uc = Unsafe.class;
56: Field[] fields = uc.getDeclaredFields();
57: for (int i = 0; i < fields.length; i++) {
58: if (fields[i].getName().equals("theUnsafe")) {
59: fields[i].setAccessible(true);
60: try {
61: return (Unsafe) fields[i].get(uc);
62: } catch (IllegalArgumentException e) {
63: throw new TCRuntimeException(e);
64: } catch (IllegalAccessException e) {
65: throw new TCRuntimeException(e);
66: }
67: }
68: }
69: return null;
70: }
71: }
|