KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > util > concurrent > MonitorUtils


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.concurrent;
5
6 import java.lang.reflect.Field JavaDoc;
7
8 import sun.misc.Unsafe;
9
10 public class MonitorUtils {
11
12   private static final Unsafe unsafe;
13
14   static {
15     try {
16       Class JavaDoc unsafeClass = Class.forName("sun.misc.Unsafe");
17       Field JavaDoc getter = unsafeClass.getDeclaredField("theUnsafe");
18       getter.setAccessible(true);
19       unsafe = (Unsafe) getter.get(null);
20     } catch (Throwable JavaDoc t) {
21       t.printStackTrace();
22       throw new RuntimeException JavaDoc("Unable to access sun.misc.Unsafe");
23     }
24   }
25
26   private MonitorUtils() {
27     // utility class -- not for instantiation
28
}
29
30   public static void monitorEnter(Object JavaDoc object) {
31     unsafe.monitorEnter(object);
32   }
33
34   public static void monitorExit(Object JavaDoc object) {
35     unsafe.monitorExit(object);
36   }
37
38   public static void monitorEnter(Object JavaDoc object, int count) {
39     for (int i = 0; i < count; i++) {
40       unsafe.monitorEnter(object);
41     }
42   }
43
44   /**
45    * Completely release the monitor on the given object (calling thread needs to own the monitor obviously)
46    *
47    * @return the number of monitorExit calls performed
48    */

49   public static int releaseMonitor(Object JavaDoc object) {
50     if (object == null) { throw new NullPointerException JavaDoc("object is null"); }
51     if (!Thread.holdsLock(object)) { throw new IllegalMonitorStateException JavaDoc("not monitor owner"); }
52
53     // This has the side effect of inflating the monitor (see VM source). It may not be necessary on all platforms (and
54
// can be optimized as such if necessary).
55
unsafe.monitorEnter(object);
56     unsafe.monitorExit(object);
57
58     int count = 0;
59     while (Thread.holdsLock(object)) {
60       unsafe.monitorExit(object);
61       count++;
62     }
63
64     return count++;
65   }
66 }
67
Popular Tags