1 4 package com.tc.util.concurrent; 5 6 import java.lang.reflect.Field ; 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 unsafeClass = Class.forName("sun.misc.Unsafe"); 17 Field getter = unsafeClass.getDeclaredField("theUnsafe"); 18 getter.setAccessible(true); 19 unsafe = (Unsafe) getter.get(null); 20 } catch (Throwable t) { 21 t.printStackTrace(); 22 throw new RuntimeException ("Unable to access sun.misc.Unsafe"); 23 } 24 } 25 26 private MonitorUtils() { 27 } 29 30 public static void monitorEnter(Object object) { 31 unsafe.monitorEnter(object); 32 } 33 34 public static void monitorExit(Object object) { 35 unsafe.monitorExit(object); 36 } 37 38 public static void monitorEnter(Object object, int count) { 39 for (int i = 0; i < count; i++) { 40 unsafe.monitorEnter(object); 41 } 42 } 43 44 49 public static int releaseMonitor(Object object) { 50 if (object == null) { throw new NullPointerException ("object is null"); } 51 if (!Thread.holdsLock(object)) { throw new IllegalMonitorStateException ("not monitor owner"); } 52 53 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 |