Java Code Examples for java.util.concurrent.locks.ReentrantLock.tryLock()

The following are Jave code examples for showing how to use tryLock() of the java.util.concurrent.locks.ReentrantLock class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: mycat-src-1.6.1-RELEASE   File: LockPerfMain.java   View Source Code Vote up 6 votes
public void tReentrantLock() {
    System.currentTimeMillis();
    ReentrantLock lock = new ReentrantLock();

    long t1 = System.currentTimeMillis();
    for (int i = 0; i < 10000000; i++) {
        if (lock.tryLock()) {
            try {
                // ...
            } finally {
                lock.unlock();
            }
        }
    }
    long t2 = System.currentTimeMillis();

    System.out.println("take time:" + (t2 - t1) + " ms.");
}
 
Example 2
Project: guava-mock   File: Monitor.java   View Source Code Vote up 6 votes
/**
 * Enters this monitor. Blocks at most the given time.
 *
 * @return whether the monitor was entered
 */
public boolean enter(long time, TimeUnit unit) {
  final long timeoutNanos = toSafeNanos(time, unit);
  final ReentrantLock lock = this.lock;
  if (!fair && lock.tryLock()) {
    return true;
  }
  boolean interrupted = Thread.interrupted();
  try {
    final long startTime = System.nanoTime();
    for (long remainingNanos = timeoutNanos; ; ) {
      try {
        return lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS);
      } catch (InterruptedException interrupt) {
        interrupted = true;
        remainingNanos = remainingNanos(startTime, timeoutNanos);
      }
    }
  } finally {
    if (interrupted) {
      Thread.currentThread().interrupt();
    }
  }
}
 
Example 3
Project: guava-mock   File: Monitor.java   View Source Code Vote up 6 votes
/**
 * 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();
    }
  }
}
 
Example 4
Project: guava-mock   File: Monitor.java   View Source Code Vote up 6 votes
/**
 * 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();
    }
  }
}
 
Example 5
Project: openjdk-jdk10   File: TimeoutLockLoops.java   View Source Code Vote up 6 votes
public final void run() {
    try {
        barrier.await();
        int sum = v;
        int x = 17;
        final ReentrantLock lock = this.lock;
        while (lock.tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
            try {
                v = x = LoopHelpers.compute1(v);
            }
            finally {
                lock.unlock();
            }
            sum += LoopHelpers.compute2(x);
        }
        barrier.await();
        result += sum;
    }
    catch (Throwable ex) {
        fail = ex;
        throw new RuntimeException(ex);
    }
}
 
Example 6
Project: googles-monorepo-demo   File: Monitor.java   View Source Code Vote up 6 votes
/**
 * Enters this monitor. Blocks at most the given time.
 *
 * @return whether the monitor was entered
 */
public boolean enter(long time, TimeUnit unit) {
  final long timeoutNanos = toSafeNanos(time, unit);
  final ReentrantLock lock = this.lock;
  if (!fair && lock.tryLock()) {
    return true;
  }
  boolean interrupted = Thread.interrupted();
  try {
    final long startTime = System.nanoTime();
    for (long remainingNanos = timeoutNanos; ; ) {
      try {
        return lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS);
      } catch (InterruptedException interrupt) {
        interrupted = true;
        remainingNanos = remainingNanos(startTime, timeoutNanos);
      }
    }
  } finally {
    if (interrupted) {
      Thread.currentThread().interrupt();
    }
  }
}
 
Example 7
Project: googles-monorepo-demo   File: Monitor.java   View Source Code Vote up 6 votes
/**
 * 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();
    }
  }
}
 
Example 8
Project: googles-monorepo-demo   File: Monitor.java   View Source Code Vote up 6 votes
/**
 * 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();
    }
  }
}
 
Example 9
Project: dble   File: LockPerfMain.java   View Source Code Vote up 6 votes
public void tReentrantLock() {
    System.currentTimeMillis();
    ReentrantLock lock = new ReentrantLock();

    long t1 = System.currentTimeMillis();
    for (int i = 0; i < 10000000; i++) {
        if (lock.tryLock()) {
            try {
                // ...
            } finally {
                lock.unlock();
            }
        }
    }
    long t2 = System.currentTimeMillis();

    System.out.println("take time:" + (t2 - t1) + " ms.");
}
 
Example 10
Project: monix-forkjoin   File: ForkJoinTask.java   View Source Code Vote up 5 votes
/**
 * 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();
        }
    }
}
 
Example 11
Project: euphrates   File: S3Writer.java   View Source Code Vote up 5 votes
public void run() {
  while (true) {
    for (ConcurrentHashMap.Entry<String, BlockingQueue<CopyJob>> copyEntry : queues.entrySet()) {
      try {
        String currentTableName = copyEntry.getKey();
        BlockingQueue<CopyJob> queue = copyEntry.getValue();

        ReentrantLock currentTableLock = tableCopyLocks.get(currentTableName);
        if (!currentTableLock.tryLock()) {
          continue;
        }

        try {
          // wait a second to take an item
          CopyJob firstJob = queue.poll(1L, TimeUnit.SECONDS);
          // when there is no item, go to the next entry in the loop
          if (firstJob == null) continue;

          Config.Table table = firstJob.getTable();
          ArrayList<CopyJob> jobs = new ArrayList<>();
          jobs.add(firstJob);
          // drain up to 9 more for 10 in total
          queue.drainTo(jobs, 9);

          processJobs(table, jobs);
        } finally {
          currentTableLock.unlock();
        }
      } catch (InterruptedException ie) {
        return; // do nothing and return
      } catch (Exception e) {
        App.fatal(e);
      }
    }
  }
}
 
Example 12
Project: OpenJSharp   File: ForkJoinTask.java   View Source Code Vote up 5 votes
/**
 * 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();
        }
    }
}
 
Example 13
Project: jdk8u-jdk   File: ForkJoinTask.java   View Source Code Vote up 5 votes
/**
 * 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();
        }
    }
}
 
Example 14
Project: openjdk-jdk10   File: ForkJoinTask.java   View Source Code Vote up 5 votes
/**
 * If lock is available, polls stale refs and removes them.
 * Called from ForkJoinPool when pools become quiescent.
 */
static final void helpExpungeStaleExceptions() {
    final ReentrantLock lock = exceptionTableLock;
    if (lock.tryLock()) {
        try {
            expungeStaleExceptions();
        } finally {
            lock.unlock();
        }
    }
}
 
Example 15
Project: android-retrostreams   File: ForkJoinTask.java   View Source Code Vote up 5 votes
/**
 * If lock is available, polls stale refs and removes them.
 * Called from ForkJoinPool when pools become quiescent.
 */
static final void helpExpungeStaleExceptions() {
    final ReentrantLock lock = exceptionTableLock;
    if (lock.tryLock()) {
        try {
            expungeStaleExceptions();
        } finally {
            lock.unlock();
        }
    }
}
 
Example 16
Project: util   File: ForkJoinTask.java   View Source Code Vote up 5 votes
/**
 * 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();
		}
	}
}
 
Example 17
Project: guava-mock   File: Monitor.java   View Source Code Vote up 4 votes
/**
 * Enters this monitor when the guard is satisfied. Blocks at most the given time, including both
 * the time to acquire the lock and the time to 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
 * @throws InterruptedException if interrupted while waiting
 */
public boolean enterWhen(Guard guard, long time, TimeUnit unit) throws InterruptedException {
  final long timeoutNanos = toSafeNanos(time, unit);
  if (guard.monitor != this) {
    throw new IllegalMonitorStateException();
  }
  final ReentrantLock lock = this.lock;
  boolean reentrant = lock.isHeldByCurrentThread();
  long startTime = 0L;

  locked:
  {
    if (!fair) {
      // Check interrupt status to get behavior consistent with fair case.
      if (Thread.interrupted()) {
        throw new InterruptedException();
      }
      if (lock.tryLock()) {
        break locked;
      }
    }
    startTime = initNanoTime(timeoutNanos);
    if (!lock.tryLock(time, unit)) {
      return false;
    }
  }

  boolean satisfied = false;
  boolean threw = true;
  try {
    satisfied =
        guard.isSatisfied()
            || awaitNanos(
                guard,
                (startTime == 0L) ? timeoutNanos : remainingNanos(startTime, timeoutNanos),
                reentrant);
    threw = false;
    return satisfied;
  } finally {
    if (!satisfied) {
      try {
        // Don't need to signal if timed out, but do if interrupted
        if (threw && !reentrant) {
          signalNextWaiter();
        }
      } finally {
        lock.unlock();
      }
    }
  }
}
 
Example 18
Project: googles-monorepo-demo   File: Monitor.java   View Source Code Vote up 4 votes
/**
 * Enters this monitor when the guard is satisfied. Blocks at most the given time, including both
 * the time to acquire the lock and the time to 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
 * @throws InterruptedException if interrupted while waiting
 */
public boolean enterWhen(Guard guard, long time, TimeUnit unit) throws InterruptedException {
  final long timeoutNanos = toSafeNanos(time, unit);
  if (guard.monitor != this) {
    throw new IllegalMonitorStateException();
  }
  final ReentrantLock lock = this.lock;
  boolean reentrant = lock.isHeldByCurrentThread();
  long startTime = 0L;

  locked:
  {
    if (!fair) {
      // Check interrupt status to get behavior consistent with fair case.
      if (Thread.interrupted()) {
        throw new InterruptedException();
      }
      if (lock.tryLock()) {
        break locked;
      }
    }
    startTime = initNanoTime(timeoutNanos);
    if (!lock.tryLock(time, unit)) {
      return false;
    }
  }

  boolean satisfied = false;
  boolean threw = true;
  try {
    satisfied =
        guard.isSatisfied()
            || awaitNanos(
                guard,
                (startTime == 0L) ? timeoutNanos : remainingNanos(startTime, timeoutNanos),
                reentrant);
    threw = false;
    return satisfied;
  } finally {
    if (!satisfied) {
      try {
        // Don't need to signal if timed out, but do if interrupted
        if (threw && !reentrant) {
          signalNextWaiter();
        }
      } finally {
        lock.unlock();
      }
    }
  }
}