java.util.concurrent.locks.ReentrantLock.tryLock()方法的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(9.3k)|赞(0)|评价(0)|浏览(157)

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

ReentrantLock.tryLock介绍

[英]Acquires the lock only if it is not held by another thread at the time of invocation.

Acquires the lock if it is not held by another thread and returns immediately with the value true, setting the lock hold count to one. Even when this lock has been set to use a fair ordering policy, a call to tryLock() will immediately acquire the lock if it is available, whether or not other threads are currently waiting for the lock. This "barging" behavior can be useful in certain circumstances, even though it breaks fairness. If you want to honor the fairness setting for this lock, then use #tryLock(long,TimeUnit)which is almost equivalent (it also detects interruption).

If the current thread already holds this lock then the hold count is incremented by one and the method returns true.

If the lock is held by another thread then this method will return immediately with the value false.
[中]仅当调用时锁未被另一个线程持有时,才获取锁。
如果锁未被另一个线程持有,则获取锁,并立即返回值true,将锁持有计数设置为1。即使将此锁设置为使用公平排序策略,调用tryLock()也会立即获取该锁(如果该锁可用),无论当前是否有其他线程正在等待该锁。这种“讨价还价”行为在某些情况下是有用的,尽管它破坏了公平。如果您想遵守此锁的公平性设置,请使用#tryLock(long,TimeUnit),它几乎是等效的(它还检测到中断)。
如果当前线程已经持有该锁,那么持有计数将增加1,并且该方法返回true。
如果锁由另一个线程持有,则此方法将立即返回值false。

代码示例

代码示例来源:origin: jenkinsci/jenkins

/**
 * Invokes the supplied {@link Runnable} if the {@link Queue} lock was obtained without blocking.
 *
 * @param runnable the operation to perform.
 * @return {@code true} if the lock was available and the operation was performed.
 * @since 1.618
 */
protected boolean _tryWithLock(Runnable runnable) {
  if (lock.tryLock()) {
    try {
      runnable.run();
    } finally {
      lock.unlock();
    }
    return true;
  } else {
    return false;
  }
}

代码示例来源:origin: apache/hbase

private void sendStopSignal() {
 if (lock.tryLock()) {
  try {
   waitCond.signalAll();
   syncCond.signalAll();
  } finally {
   lock.unlock();
  }
 }
}

代码示例来源:origin: alipay/sofa-rpc

@Override
public void clear() {
  lock.tryLock();
  try {
    kvMap.clear();
    vkMap.clear();
  } finally {
    lock.unlock();
  }
}

代码示例来源:origin: alipay/sofa-rpc

@Override
public void clear() {
  lock.tryLock();
  try {
    kvMap.clear();
    vkMap.clear();
  } finally {
    lock.unlock();
  }
}

代码示例来源:origin: spring-projects/spring-framework

public void removeExpiredSessions(Instant now) {
    if (sessions.isEmpty()) {
      return;
    }
    if (this.lock.tryLock()) {
      try {
        Iterator<InMemoryWebSession> iterator = sessions.values().iterator();
        while (iterator.hasNext()) {
          InMemoryWebSession session = iterator.next();
          if (session.isExpired(now)) {
            iterator.remove();
            session.invalidate();
          }
        }
      }
      finally {
        this.checkTime = now.plus(CHECK_PERIOD, ChronoUnit.MILLIS);
        this.lock.unlock();
      }
    }
  }
}

代码示例来源:origin: google/guava

/**
 * Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the
 * lock, but does not wait for the guard to be satisfied, and may be interrupted.
 *
 * @return whether the monitor was entered, which guarantees that the guard is now satisfied
 */
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public boolean enterIfInterruptibly(Guard guard, long time, TimeUnit unit)
  throws InterruptedException {
 if (guard.monitor != this) {
  throw new IllegalMonitorStateException();
 }
 final ReentrantLock lock = this.lock;
 if (!lock.tryLock(time, unit)) {
  return false;
 }
 boolean satisfied = false;
 try {
  return satisfied = guard.isSatisfied();
 } finally {
  if (!satisfied) {
   lock.unlock();
  }
 }
}

代码示例来源:origin: google/guava

/**
 * Enters this monitor if it is possible to do so immediately and the guard is satisfied. Does not
 * block acquiring the lock and does not wait for the guard to be satisfied.
 *
 * <p><b>Note:</b> This method disregards the fairness setting of this monitor.
 *
 * @return whether the monitor was entered, which guarantees that the guard is now satisfied
 */
public boolean tryEnterIf(Guard guard) {
 if (guard.monitor != this) {
  throw new IllegalMonitorStateException();
 }
 final ReentrantLock lock = this.lock;
 if (!lock.tryLock()) {
  return false;
 }
 boolean satisfied = false;
 try {
  return satisfied = guard.isSatisfied();
 } finally {
  if (!satisfied) {
   lock.unlock();
  }
 }
}

代码示例来源:origin: apache/hive

private int allocateFast(int freeListIx, MemoryBuffer[] dest, long[] destHeaders,
  int destIx, int destCount, int allocSize) {
 if (data == null) return -1; // not allocated yet
 FreeList freeList = freeLists[freeListIx];
 if (!freeList.lock.tryLock()) return destIx;
 try {
  return allocateFromFreeListUnderLock(
    freeList, freeListIx, dest, destHeaders, destIx, destCount, allocSize);
 } finally {
  freeList.lock.unlock();
 }
}

代码示例来源:origin: prestodb/presto

/**
 * Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the
 * lock, but does not wait for the guard to be satisfied, and may be interrupted.
 *
 * @return whether the monitor was entered, which guarantees that the guard is now satisfied
 */
public boolean enterIfInterruptibly(Guard guard, long time, TimeUnit unit)
  throws InterruptedException {
 if (guard.monitor != this) {
  throw new IllegalMonitorStateException();
 }
 final ReentrantLock lock = this.lock;
 if (!lock.tryLock(time, unit)) {
  return false;
 }
 boolean satisfied = false;
 try {
  return satisfied = guard.isSatisfied();
 } finally {
  if (!satisfied) {
   lock.unlock();
  }
 }
}

代码示例来源:origin: h2oai/h2o-2

/**
 * If lock is available, poll stale refs and remove them.
 * Called from ForkJoinPool when pools become quiescent.
 */
static final void helpExpungeStaleExceptions() {
  final ReentrantLock lock = exceptionTableLock;
  if (lock.tryLock()) {
    try {
      expungeStaleExceptions();
    } finally {
      lock.unlock();
    }
  }
}

代码示例来源:origin: prestodb/presto

/**
 * Enters this monitor if it is possible to do so immediately and the guard is satisfied. Does not
 * block acquiring the lock and does not wait for the guard to be satisfied.
 *
 * <p><b>Note:</b> This method disregards the fairness setting of this monitor.
 *
 * @return whether the monitor was entered, which guarantees that the guard is now satisfied
 */
public boolean tryEnterIf(Guard guard) {
 if (guard.monitor != this) {
  throw new IllegalMonitorStateException();
 }
 final ReentrantLock lock = this.lock;
 if (!lock.tryLock()) {
  return false;
 }
 boolean satisfied = false;
 try {
  return satisfied = guard.isSatisfied();
 } finally {
  if (!satisfied) {
   lock.unlock();
  }
 }
}

代码示例来源:origin: org.apache.lucene/lucene-core

void tryPurge(IOUtils.IOConsumer<FlushTicket> consumer) throws IOException {
 assert !Thread.holdsLock(this);
 if (purgeLock.tryLock()) {
  try {
   innerPurge(consumer);
  } finally {
   purgeLock.unlock();
  }
 }
}

代码示例来源:origin: LeonardoZ/java-concurrency-patterns

/**
 * Try lock - Timed and polled lock acquisition
 * 
 * @throws InterruptedException
 */
public void lockMyHearthWithTiming() throws InterruptedException {
  // Tries to acquire lock in the specified timeout
  if (!reentrantLock.tryLock(1l, TimeUnit.SECONDS)) {
    System.err.println("Failed to acquire the lock - it's already held.");
  } else {
    try {
      System.out.println("Simulating a blocking computation - forcing tryLock() to fail");
      Thread.sleep(3000);
    } finally {
      reentrantLock.unlock();
    }
  }
}

代码示例来源:origin: robovm/robovm

/**
 * If lock is available, poll stale refs and remove them.
 * Called from ForkJoinPool when pools become quiescent.
 */
static final void helpExpungeStaleExceptions() {
  final ReentrantLock lock = exceptionTableLock;
  if (lock.tryLock()) {
    try {
      expungeStaleExceptions();
    } finally {
      lock.unlock();
    }
  }
}

代码示例来源:origin: com.typesafe.akka/akka-actor_2.11

/**
 * If lock is available, poll stale refs and remove them.
 * Called from ForkJoinPool when pools become quiescent.
 */
static final void helpExpungeStaleExceptions() {
  final ReentrantLock lock = exceptionTableLock;
  if (lock.tryLock()) {
    try {
      expungeStaleExceptions();
    } finally {
      lock.unlock();
    }
  }
}

代码示例来源:origin: com.typesafe.akka/akka-actor_2.12

/**
 * If lock is available, poll stale refs and remove them.
 * Called from ForkJoinPool when pools become quiescent.
 */
static final void helpExpungeStaleExceptions() {
  final ReentrantLock lock = exceptionTableLock;
  if (lock.tryLock()) {
    try {
      expungeStaleExceptions();
    } finally {
      lock.unlock();
    }
  }
}

代码示例来源:origin: com.typesafe.akka/akka-actor

/**
 * If lock is available, poll stale refs and remove them.
 * Called from ForkJoinPool when pools become quiescent.
 */
static final void helpExpungeStaleExceptions() {
  final ReentrantLock lock = exceptionTableLock;
  if (lock.tryLock()) {
    try {
      expungeStaleExceptions();
    } finally {
      lock.unlock();
    }
  }
}

代码示例来源:origin: org.springframework/spring-web

public void removeExpiredSessions(Instant now) {
    if (sessions.isEmpty()) {
      return;
    }
    if (this.lock.tryLock()) {
      try {
        Iterator<InMemoryWebSession> iterator = sessions.values().iterator();
        while (iterator.hasNext()) {
          InMemoryWebSession session = iterator.next();
          if (session.isExpired(now)) {
            iterator.remove();
            session.invalidate();
          }
        }
      }
      finally {
        this.checkTime = now.plus(CHECK_PERIOD, ChronoUnit.MILLIS);
        this.lock.unlock();
      }
    }
  }
}

代码示例来源:origin: wildfly/wildfly

/**
 * Enters this monitor if it is possible to do so immediately and the guard is satisfied. Does not
 * block acquiring the lock and does not wait for the guard to be satisfied.
 *
 * <p><b>Note:</b> This method disregards the fairness setting of this monitor.
 *
 * @return whether the monitor was entered, which guarantees that the guard is now satisfied
 */
public boolean tryEnterIf(Guard guard) {
 if (guard.monitor != this) {
  throw new IllegalMonitorStateException();
 }
 final ReentrantLock lock = this.lock;
 if (!lock.tryLock()) {
  return false;
 }
 boolean satisfied = false;
 try {
  return satisfied = guard.isSatisfied();
 } finally {
  if (!satisfied) {
   lock.unlock();
  }
 }
}

代码示例来源:origin: wildfly/wildfly

/**
 * Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the
 * lock, but does not wait for the guard to be satisfied, and may be interrupted.
 *
 * @return whether the monitor was entered, which guarantees that the guard is now satisfied
 */
public boolean enterIfInterruptibly(Guard guard, long time, TimeUnit unit)
  throws InterruptedException {
 if (guard.monitor != this) {
  throw new IllegalMonitorStateException();
 }
 final ReentrantLock lock = this.lock;
 if (!lock.tryLock(time, unit)) {
  return false;
 }
 boolean satisfied = false;
 try {
  return satisfied = guard.isSatisfied();
 } finally {
  if (!satisfied) {
   lock.unlock();
  }
 }
}

相关文章