sun.misc.Unsafe.tryMonitorEnter()方法的使用及代码示例

x33g5p2x  于2022-01-31 转载在 其他  
字(2.0k)|赞(0)|评价(0)|浏览(126)

本文整理了Java中sun.misc.Unsafe.tryMonitorEnter()方法的一些代码示例,展示了Unsafe.tryMonitorEnter()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Unsafe.tryMonitorEnter()方法的具体详情如下:
包路径:sun.misc.Unsafe
类名称:Unsafe
方法名:tryMonitorEnter

Unsafe.tryMonitorEnter介绍

[英]Tries to lock the object. Returns true or false to indicate whether the lock succeeded. If it did, the object must be unlocked via #monitorExit.
[中]试图锁定对象。返回true或false以指示锁定是否成功。如果是,则必须通过#monitorExit解锁对象。

代码示例

代码示例来源:origin: kabutz/javaspecialists

public static boolean trySynchronize(Object monitor) {
  return unsafe.tryMonitorEnter(monitor);
}

代码示例来源:origin: com.tomitribe.tribestream/tribestream-metrics-bytecode

public static boolean tryMonitorEnter(final Object o) {
  return UNSAFE.tryMonitorEnter(o);
}

代码示例来源:origin: GeeQuery/ef-orm

/**
 * 在执行一个同步方法前,可以手工得到锁。<p>
 * 
 * 这个方法可以让你在进入同步方法或同步块之前多一个选择的机会。因为这个方法不会阻塞,如果锁无法得到,会返回false。
 * 如果返回true,证明你可以无阻塞的进入后面的同步方法或同步块。<p>
 * 
 * 要注意,用这个方法得到的锁不会自动释放(比如在同步块执行完毕后不会释放),必须通过调用unlock(Object)方法才能释放。 需小心使用。<p>
 * 
 * @param obj
 * @return 如果锁得到了,返回true,如果锁没有得到到返回false
 */
@SuppressWarnings("restriction")
public static boolean tryLock(Object obj) {
  sun.misc.Unsafe unsafe = UnsafeUtils.getUnsafe();
  return unsafe.tryMonitorEnter(obj);
}

代码示例来源:origin: stackoverflow.com

private static sun.misc.Unsafe getUnsafe() {
  try {
    Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
    field.setAccessible(true);
    return (Unsafe) field.get(null);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

public void doSomething() {
 Object record = new Object();
 sun.misc.Unsafe unsafe = getUnsafe(); 
 if (unsafe.tryMonitorEnter(record)) {
  try {
   // record is locked - perform operations on it
  } finally {
   unsafe.monitorExit(record);
  }
 } else {
   // could not lock record
 }
}

代码示例来源:origin: GeeQuery/ef-orm

/**
 * 判断当前该对象是否已锁。<br> 注意在并发场景下,这一操作只能反映瞬时的状态,仅用于检测,并不能认为本次检测该锁空闲,紧接着的代码就能得到锁。
 * 
 * @param obj
 * @return
 */
@SuppressWarnings("restriction")
public static boolean isLocked(Object obj) {
  sun.misc.Unsafe unsafe = UnsafeUtils.getUnsafe();
  if (unsafe.tryMonitorEnter(obj)) {
    unsafe.monitorExit(obj);
    return false;
  }
  return true;
}

相关文章

微信公众号

最新文章

更多

Unsafe类方法