Tabnine Logo
ReentrantLock
Code IndexAdd Tabnine to your IDE (free)

How to use
ReentrantLock
in
java.util.concurrent.locks

Best Java code snippets using java.util.concurrent.locks.ReentrantLock (Showing top 20 results out of 16,803)

Refine searchRefine arrow

  • Condition
  • AtomicInteger
  • TimeUnit
  • Lock
  • AtomicBoolean
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();
  }
}

java.util.concurrent.locksReentrantLock

Javadoc

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.

Most used methods

  • unlock
    Attempts to release this lock.If the current thread is the holder of this lock then the hold count i
  • lock
    Acquires the lock.Acquires the lock if it is not held by another thread and returns immediately, set
  • <init>
    Creates an instance of ReentrantLock with the given fairness policy.
  • tryLock
    Acquires the lock if it is not held by another thread within the given waiting time and the current
  • isHeldByCurrentThread
    Queries if this lock is held by the current thread.Analogous to the Thread#holdsLock method for buil
  • lockInterruptibly
    Acquires the lock unless the current thread is Thread#interrupt.Acquires the lock if it is not held
  • newCondition
    Returns a Condition instance for use with this Lock instance.The returned Condition instance support
  • isLocked
    Queries if this lock is held by any thread. This method is designed for use in monitoring of the sys
  • getHoldCount
    Queries the number of holds on this lock by the current thread.A thread has a hold on a lock for eac
  • hasQueuedThreads
    Queries whether any threads are waiting to acquire this lock. Note that because cancellations may oc
  • getQueueLength
    Returns an estimate of the number of threads waiting to acquire this lock. The value is only an esti
  • hasQueuedThread
    Queries whether the given thread is waiting to acquire this lock. Note that because cancellations ma
  • getQueueLength,
  • hasQueuedThread,
  • hasWaiters,
  • getOwner,
  • isFair,
  • getWaitQueueLength,
  • toString,
  • getQueuedThreads,
  • getWaitingThreads

Popular in Java

  • Start an intent from android
  • getSharedPreferences (Context)
  • addToBackStack (FragmentTransaction)
  • notifyDataSetChanged (ArrayAdapter)
  • FileNotFoundException (java.io)
    Thrown when a file specified by a program cannot be found.
  • HttpURLConnection (java.net)
    An URLConnection for HTTP (RFC 2616 [http://tools.ietf.org/html/rfc2616]) used to send and receive d
  • Format (java.text)
    The base class for all formats. This is an abstract base class which specifies the protocol for clas
  • BitSet (java.util)
    The BitSet class implements abit array [http://en.wikipedia.org/wiki/Bit_array]. Each element is eit
  • JCheckBox (javax.swing)
  • Option (scala)
  • CodeWhisperer alternatives
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now