KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > util > UnsafeUtil


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

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 JavaDoc;
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 JavaDoc CLASS_SLASH = "com/tc/util/UnsafeUtil";
19   public final static String JavaDoc 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 JavaDoc obj, long fieldOffset, Object JavaDoc update) {
27     TCObject tcObject = ManagerUtil.lookupExistingOrNull(obj);
28     if (tcObject == null) { throw new NullPointerException JavaDoc("Object is not a DSO shared object."); }
29     tcObject.objectFieldChangedByOffset(obj.getClass().getName(), fieldOffset, update, -1);
30   }
31
32   public static void setField(Object JavaDoc obj, Field JavaDoc field, Object JavaDoc value) {
33     long offset = unsafe.objectFieldOffset(field);
34     unsafe.putObject(obj, offset, value);
35   }
36   
37   public static void monitorEnter(Object JavaDoc obj) {
38     unsafe.monitorEnter(obj);
39   }
40   
41   public static void monitorExit(Object JavaDoc obj) {
42     unsafe.monitorExit(obj);
43   }
44
45   public static Unsafe getUnsafe() {
46     return unsafe;
47   }
48
49   private static Unsafe findUnsafe() {
50     Class JavaDoc uc = Unsafe.class;
51     Field JavaDoc[] 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 JavaDoc e) {
58           throw new TCRuntimeException(e);
59         } catch (IllegalAccessException JavaDoc e) {
60           throw new TCRuntimeException(e);
61         }
62       }
63     }
64     return null;
65   }
66 }
67
Popular Tags