java.util.concurrent.locks.ReentrantLock类的使用及代码示例

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

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

ReentrantLock介绍

[英]A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.

A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock. This can be checked using methods #isHeldByCurrentThread, and #getHoldCount.

The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. Note however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock. Also note that the untimed #tryLock() method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting.

It is recommended practice to always immediately follow a call to lock with a try block, most typically in a before/after construction such as:

class X finally  
lock.unlock() 
} 
} 
}}

In addition to implementing the Lock interface, this class defines a number of public and protectedmethods for inspecting the state of the lock. Some of these methods are only useful for instrumentation and monitoring.

Serialization of this class behaves in the same way as built-in locks: a deserialized lock is in the unlocked state, regardless of its state when serialized.

This lock supports a maximum of 2147483647 recursive locks by the same thread. Attempts to exceed this limit result in Error throws from locking methods.
[中]一个可重入互斥锁,其基本行为和语义与使用同步方法和语句访问的隐式监视锁相同,但具有扩展功能。
ReentrantLock由上次成功锁定但尚未解锁的线程拥有。当锁不属于另一个线程时,调用锁的线程将返回并成功获取锁。如果当前线程已经拥有锁,该方法将立即返回。这可以使用#isHeldByCurrentThread和#getHoldCount方法进行检查。
此类的构造函数接受可选的Fairity参数。当设置为true时,在争用状态下,锁有利于向等待时间最长的线程授予访问权限。否则,该锁不保证任何特定的访问顺序。与使用默认设置的程序相比,使用由多个线程访问的公平锁的程序可能会显示较低的总体吞吐量(即较慢;通常要慢得多),但在获得锁和保证没有饥饿的时间上差异较小。但是请注意,锁的公平性并不能保证线程调度的公平性。因此,使用公平锁的多个线程中的一个可能会连续多次获得公平锁,而其他活动线程则不会继续进行,当前也不会持有该锁。还要注意,untimed#tryLock()方法不支持公平性设置。如果锁可用,即使其他线程正在等待,它也会成功。
建议在调用后立即始终使用try块锁定,最典型的是在构建之前/之后,例如:

class X finally  
lock.unlock() 
} 
} 
}}

除了实现锁接口之外,这个类还定义了许多用于检查锁状态的公共和受保护方法。其中一些方法仅适用于仪器和监测。
此类的序列化与内置锁的行为相同:反序列化的锁处于解锁状态,而不管序列化时的状态如何。
此锁最多支持同一线程的2147483647个递归锁。试图超过此限制将导致锁定方法引发错误。

代码示例

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

@Override
public boolean isCancelled() {
 lock.lock();
 try {
  return currentFuture.isCancelled();
 } finally {
  lock.unlock();
 }
}

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

@Override
 public Lock get() {
  return new ReentrantLock(false);
 }
});

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

/**
 * Enters this monitor. Blocks at most the given time, and may be interrupted.
 *
 * @return whether the monitor was entered
 * @throws InterruptedException if interrupted while waiting
 */
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public boolean enterInterruptibly(long time, TimeUnit unit) throws InterruptedException {
 return lock.tryLock(time, unit);
}

代码示例来源:origin: alibaba/druid

public DruidAbstractDataSource(boolean lockFair){
  lock = new ReentrantLock(lockFair);
  notEmpty = lock.newCondition();
  empty = lock.newCondition();
}

代码示例来源:origin: alibaba/druid

public void setEnable(boolean enable) {
  lock.lock();
  try {
    this.enable = enable;
    if (!enable) {
      notEmpty.signalAll();
      notEmptySignalCount++;
    }
  } finally {
    lock.unlock();
  }
}

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

AtomicBoolean txnFail = new AtomicBoolean(false);
AtomicInteger callbacksReceived = new AtomicInteger(0);
AtomicInteger callbacksExpected = new AtomicInteger(0);
final Lock lock = new ReentrantLock();
final Condition condition = lock.newCondition();
if (incrementBuffer != null) {
 incrementBuffer.clear();
   List<PutRequest> actions = serializer.getActions();
   List<AtomicIncrementRequest> increments = serializer.getIncrements();
   callbacksExpected.addAndGet(actions.size());
   if (!batchIncrements) {
    callbacksExpected.addAndGet(increments.size());
 lock.unlock();

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

private Lock lock = new ReentrantLock();
private Condition notFull = lock.newCondition();
private Condition notEmpty = lock.newCondition();
  lock.lock();
  try {
    while(queue.size() == capacity) {
      notFull.await();
    notEmpty.signal();
  } finally {
    lock.unlock();
  try {
    while(queue.isEmpty()) {
      notEmpty.await();

代码示例来源:origin: alibaba/jvm-sandbox

@Override
  public void onEvent(Event event) throws Throwable {
    final BeforeEvent bEvent = (BeforeEvent) event;
    printer.println(String.format(
        "%s.%s will be delay %s(ms) on %s",
        bEvent.javaClassName,
        bEvent.javaMethodName,
        delayMs,
        Thread.currentThread().getName()
    ));
    delayLock.lock();
    try {
      // 如果已经结束,则放弃本次请求
      if (isFinishRef.get()) {
        return;
      }
      delayCondition.await(delayMs, TimeUnit.MILLISECONDS);
    } finally {
      delayLock.unlock();
    }
  }
}, BEFORE);

代码示例来源:origin: code4craft/webmagic

public void execute(final Runnable runnable) {
  if (threadAlive.get() >= threadNum) {
    try {
      reentrantLock.lock();
      while (threadAlive.get() >= threadNum) {
        try {
          condition.await();
        } catch (InterruptedException e) {
      reentrantLock.unlock();
  threadAlive.incrementAndGet();
  executorService.execute(new Runnable() {
    @Override

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

@Override
 public void run() {
  try {
   lock.lock();
   try {
    while (!started.get()) {
     startCondition.await();
    }
   } finally {
    lock.unlock();
   }
   pruner.prune();
   lock.lock();
   try {
    ended.set(true);
    endCondition.signal();
   } finally {
    lock.unlock();
   }
  } catch (SerDeException | IOException | InterruptedException | HiveException e) {
   inError.set(true);
  }
 }
}

代码示例来源:origin: jeasonlzy/okhttp-OkGo

public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
  if (e == null) throw new NullPointerException();
  long nanos = unit.toNanos(timeout);
  int c = -1;
  final ReentrantLock putLock = this.putLock;
  final AtomicInteger count = this.count;
  putLock.lockInterruptibly();
  try {
    while (count.get() == capacity) {
      if (nanos <= 0) return false;
      nanos = notFull.awaitNanos(nanos);
    }
    opQueue(new Node<E>(e));
    c = count.getAndIncrement();
    if (c + 1 < capacity) notFull.signal();
  } finally {
    putLock.unlock();
  }
  if (c == 0) signalNotEmpty();
  return true;
}

代码示例来源:origin: jeasonlzy/okhttp-OkGo

public boolean offer(E e) {
  if (e == null) throw new NullPointerException();
  final AtomicInteger count = this.count;
  if (count.get() == capacity) return false;
  int c = -1;
  Node<E> node = new Node<E>(e);
  final ReentrantLock putLock = this.putLock;
  putLock.lock();
  try {
    if (count.get() < capacity) {
      opQueue(node);
      c = count.getAndIncrement();
      if (c + 1 < capacity) notFull.signal();
    }
  } finally {
    putLock.unlock();
  }
  if (c == 0) signalNotEmpty();
  return c >= 0;
}

代码示例来源:origin: jeasonlzy/okhttp-OkGo

public void put(E e) throws InterruptedException {
  if (e == null) throw new NullPointerException();
  // Note: convention in all put/take/etc is to preset local var
  // holding count negative to indicate failure unless set.
  int c = -1;
  Node<E> node = new Node<E>(e);
  final ReentrantLock putLock = this.putLock;
  final AtomicInteger count = this.count;
  putLock.lockInterruptibly();
  try {
    while (count.get() == capacity) {
      notFull.await();
    }
    opQueue(node);
    c = count.getAndIncrement();
    if (c + 1 < capacity) notFull.signal();
  } finally {
    putLock.unlock();
  }
  if (c == 0) signalNotEmpty();
}

代码示例来源:origin: jeasonlzy/okhttp-OkGo

public E poll() {
  final AtomicInteger count = this.count;
  if (count.get() == 0) return null;
  E x = null;
  int c = -1;
  final ReentrantLock takeLock = this.takeLock;
  takeLock.lock();
  try {
    if (count.get() > 0) {
      x = opQueue(null);
      c = count.getAndDecrement();
      if (c > 1) notEmpty.signal();
    }
  } finally {
    takeLock.unlock();
  }
  if (c == capacity) signalNotFull();
  return x;
}

代码示例来源:origin: apache/incubator-druid

@Nullable
private T pollObject(long timeoutMs) throws InterruptedException
{
 long nanos = TIME_UNIT.toNanos(timeoutMs);
 final ReentrantLock lock = this.lock;
 lock.lockInterruptibly();
 try {
  while (objects.isEmpty()) {
   if (nanos <= 0) {
    return null;
   }
   nanos = notEnough.awaitNanos(nanos);
  }
  return objects.pop();
 }
 finally {
  lock.unlock();
 }
}

代码示例来源:origin: org.apache.spark/spark-core_2.11

private void waitForAsyncReadComplete() throws IOException {
 stateChangeLock.lock();
 isWaiting.set(true);
 try {
  // There is only one reader, and one writer, so the writer should signal only once,
  // but a while loop checking the wake up condition is still needed to avoid spurious wakeups.
  while (readInProgress) {
   asyncReadComplete.await();
  }
 } catch (InterruptedException e) {
  InterruptedIOException iio = new InterruptedIOException(e.getMessage());
  iio.initCause(e);
  throw iio;
 } finally {
  isWaiting.set(false);
  stateChangeLock.unlock();
 }
 checkReadException();
}

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

@Override
public void killTask() {
 lock.lock();
 try {
  wasKilled.set(true);
  shouldSleep = false;
  sleepCondition.signal();
 } finally {
  lock.unlock();
 }
}

代码示例来源:origin: jeasonlzy/okhttp-OkGo

public E take() throws InterruptedException {
  E x;
  int c = -1;
  final AtomicInteger count = this.count;
  final ReentrantLock takeLock = this.takeLock;
  takeLock.lockInterruptibly();
  try {
    while (count.get() == 0) {
      notEmpty.await();
    }
    x = opQueue(null);
    c = count.getAndDecrement();
    if (c > 1) notEmpty.signal();
  } finally {
    takeLock.unlock();
  }
  if (c == capacity) signalNotFull();
  return x;
}

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

public boolean awaitTermination(long timeout, TimeUnit unit)
  throws InterruptedException {
  long nanos = unit.toNanos(timeout);
  final ReentrantLock mainLock = this.mainLock;
  mainLock.lock();
  try {
    for (;;) {
      if (runStateAtLeast(ctl.get(), TERMINATED))
        return true;
      if (nanos <= 0)
        return false;
      nanos = termination.awaitNanos(nanos);
    }
  } finally {
    mainLock.unlock();
  }
}

代码示例来源:origin: ninjaframework/ninja

/**
 * Usually this method is called by an external component that watches
 * a directory to restart Ninja's dev mode.
 * 
 * The restart will be executed with a delay. If a bunch of files are
 * changed at the same time only one restart is performed.
 * 
 */
public void trigger() {
  // signal for a restart
  this.restartLock.lock();
  try {
    // accumulate restart triggers (e.g. # of files changed)
    accumulatedTriggerCount.incrementAndGet();
    this.restartRequested.signal();
  } finally {
    this.restartLock.unlock();
  }
}

相关文章