當前位置: 首頁>>代碼示例>>Java>>正文


Java Lock.tryLock方法代碼示例

本文整理匯總了Java中java.util.concurrent.locks.Lock.tryLock方法的典型用法代碼示例。如果您正苦於以下問題:Java Lock.tryLock方法的具體用法?Java Lock.tryLock怎麽用?Java Lock.tryLock使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.util.concurrent.locks.Lock的用法示例。


在下文中一共展示了Lock.tryLock方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: tryLock

import java.util.concurrent.locks.Lock; //導入方法依賴的package包/類
/**
 * Try to get a lock in the given number of milliseconds or get an exception
 * 
 * @param lock                          the lock to try
 * @param timeoutMs                     the number of milliseconds to try
 * @param useCase                       {@link String} value which specifies description of use case when lock is needed
 * @throws LockTryException    the exception if the time is exceeded or the thread is interrupted
 */
public static void tryLock(Lock lock, long timeoutMs, String useCase) throws LockTryException
{
    boolean gotLock = false;
    try
    {
        gotLock = lock.tryLock(timeoutMs, TimeUnit.MILLISECONDS);
    }
    catch (InterruptedException e)
    {
        // Handled
    }
    if (!gotLock)
    {
        throw new LockTryException("Failed to get lock " + lock.getClass().getSimpleName() + " for " + useCase + " in " + timeoutMs + "ms.");
    }
}
 
開發者ID:Alfresco,項目名稱:alfresco-core,代碼行數:25,代碼來源:LockHelper.java

示例2: testTryLock

import java.util.concurrent.locks.Lock; //導入方法依賴的package包/類
/**
 * Case2: Test for tryLock()
 */
@Test
public void testTryLock() {
    // generate lock in a free way, you should specify lock type, target, lease time, lease unit
    Lock lock = lockGenerator.gen("FAKE_LOCK", "A_TARGET", 1, TimeUnit.SECONDS);

    if (lock.tryLock()) {
        try {
            doYourWork();
        } finally {
            lock.unlock();
        }
    } else {
        // perform alternative actions
    }
}
 
開發者ID:baidu,項目名稱:dlock,代碼行數:19,代碼來源:DLockSimpleTest.java

示例3: runWithLock

import java.util.concurrent.locks.Lock; //導入方法依賴的package包/類
@SneakyThrows
public static <R, E extends Exception> R runWithLock(Lock lock, long maxWaitTime, ReturnableTask<R, E> task) {
    log.info("Try to lock git repository");
    if (lock.tryLock(maxWaitTime, TimeUnit.SECONDS)) {
        log.info("Git repository locked");
        try {
            return task.execute();
        } finally {
            log.info("Try to unlock git repository");
            lock.unlock();
            log.info("Git repository unlocked");
        }
    } else {
        throw new IllegalMonitorStateException("Git repository locked");
    }
}
 
開發者ID:xm-online,項目名稱:xm-ms-config,代碼行數:17,代碼來源:LockUtils.java

示例4: tryLock

import java.util.concurrent.locks.Lock; //導入方法依賴的package包/類
/**
 * 鎖
 *
 * @param lock    鎖
 * @param timeout 超時時間
 *                <li>>0 等待超時時間</li>
 *                <li>=0 無限等待</li>
 *                <li><0 無限等待</li>
 * @return 剩餘的超時時間
 * <li>>0 鎖成功,timeout>0,剩餘超時時間</li>
 * <li>0 鎖成功,timeout=0</li>
 * <li>-1 鎖成功,timeout<0</li>
 *
 */
public static long tryLock(final Lock lock, final long timeout) {
    long time;
    if (timeout > 0) {
        time = JSFContext.systemClock.now();
        try {
            if (lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
                time = timeout - (JSFContext.systemClock.now() - time);
                if (time > 0) {
                    return time;
                }else{
                    lock.unlock();
                }
            }
            return LOCK_FAIL;
        } catch (InterruptedException e) {
            return LOCK_FAIL;
        }
    } else {
        lock.lock();
        return timeout == 0 ? 0 : -1;
    }
}
 
開發者ID:tiglabs,項目名稱:jsf-sdk,代碼行數:37,代碼來源:LockUtil.java

示例5: testTryLock

import java.util.concurrent.locks.Lock; //導入方法依賴的package包/類
@Test
public void testTryLock() throws Exception {
  SemaphoreReadWriteLock rwl = new SemaphoreReadWriteLock();
  final Lock rl = rwl.readLock();
  final Lock wl = rwl.writeLock();
  assertTrue(wl.tryLock());

  final AtomicBoolean failed = new AtomicBoolean(false);

  Thread reader = new Thread(new Runnable() {
    @Override
    public void run() {
      waitToLock.countDown();
      if (rl.tryLock()) {
        failed.set(true);
      }
      latch.countDown();
    }
  });
  reader.start();

  assertTrue(waitToLock.await(OPERATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
  assertTrue(latch.await(OPERATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
  assertFalse(failed.get());
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:26,代碼來源:SemaphoreReadWriteLockJUnitTest.java

示例6: testReentrantLock

import java.util.concurrent.locks.Lock; //導入方法依賴的package包/類
/**
 * Tests GEM-96/GEODE-678
 */
@Test
public void testReentrantLock() throws Exception {

  Assert.assertEquals(Scope.GLOBAL, region.getAttributes().getScope());

  final Lock lock1 = region.getDistributedLock(id);
  final Lock lock2 = region.getDistributedLock(id);

  for (int i = 0; i < 50; i++) {
    lock1.lock();
    boolean reenteredLock = false;
    try {
      reenteredLock = lock2.tryLock(1, TimeUnit.NANOSECONDS);
      if (!reenteredLock) {
        System.out.println("ERROR: could not reenter lock");
      }
      Assert.assertTrue("Failed getting lock at 2:" + i, reenteredLock);
    } finally {
      if (reenteredLock) {
        lock2.unlock();
      }
      lock1.unlock();
    }
  }
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:29,代碼來源:DLockReentrantLockJUnitTest.java

示例7: interruptibleReaderView

import java.util.concurrent.locks.Lock; //導入方法依賴的package包/類
static Reader interruptibleReaderView(final StampedLock sl,
                                      final long timeout,
                                      final TimeUnit unit,
                                      final Phaser gate) {
    return new Reader("InterruptibleReaderView") { public void run() {
        if (gate != null ) toTheStartingGate(gate);
        final Lock rl = sl.asReadLock();

        try {
            if (timeout < 0)
                rl.lockInterruptibly();
            else
                rl.tryLock(timeout, unit);
            stamp(1L);  // got the lock
            check(sl.isReadLocked());
            check(!sl.isWriteLocked());
        } catch (Throwable x) { thrown(x);
        } finally { if (stamp() != 0L) rl.unlock(); } }};
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:20,代碼來源:Basic.java

示例8: interruptibleWriterView

import java.util.concurrent.locks.Lock; //導入方法依賴的package包/類
static Writer interruptibleWriterView(final StampedLock sl,
                                      final long timeout,
                                      final TimeUnit unit,
                                      final Phaser gate) {
    return new Writer("InterruptibleWriterView") { public void run() {
        if (gate != null ) toTheStartingGate(gate);
        Lock wl = sl.asWriteLock();
        try {
            if (timeout < 0)
                wl.lockInterruptibly();
            else
                wl.tryLock(timeout, unit);
            stamp(1L);  // got the lock
            check(!sl.isReadLocked());
            check(sl.isWriteLocked());
        } catch (Throwable x) { thrown(x);
        } finally { if (stamp() != 0L) wl.unlock(); } }};
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:19,代碼來源:Basic.java

示例9: tryLock

import java.util.concurrent.locks.Lock; //導入方法依賴的package包/類
public static @Nullable Locker tryLock(Lock lock) {
    return lock.tryLock() ? new Locker(lock) : null;
}
 
開發者ID:OvercastNetwork,項目名稱:ProjectAres,代碼行數:4,代碼來源:Locker.java

示例10: handleConnectLost

import java.util.concurrent.locks.Lock; //導入方法依賴的package包/類
/**
 * Handle connection lost condition
 * Both when received DISCONNECT message or not
 *
 * @param ctx Session
 * @return True client is marked as disconnected, False client already re-connected
 */
protected boolean handleConnectLost(ChannelHandlerContext ctx) {
    boolean redirect = false;

    // ============================== LOCK LOCK LOCK ==============================

    Lock lock = this.redis.getLock(this.clientId);

    try {
        if (!lock.tryLock(5, TimeUnit.SECONDS)) {
            logger.warn("Lock failed: Failed to lock on client {}", this.clientId);
        } else {
            logger.trace("Lock succeed: Successful lock on client {}", this.clientId);

            // Test if client already reconnected to this broker
            if (this.registry.removeSession(this.clientId, ctx)) {

                // Test if client already reconnected to another broker
                if (this.redis.removeConnectedNode(this.clientId, this.brokerId)) {

                    redirect = true;

                    // Remove connected node
                    logger.trace("Remove node: Mark client {} disconnected from broker {}", this.clientId, this.brokerId);

                    // If CleanSession is set to 1, the Client and Server MUST discard any previous Session and start a new
                    // one. This Session lasts as long as the Network Connection. State data associated with this Session
                    // MUST NOT be reused in any subsequent Session.
                    // When CleanSession is set to 1 the Client and Server need not process the deletion of state atomically.
                    if (this.cleanSession) {
                        logger.trace("Clear session: Clear session state for client {} because current connection is clean session", this.clientId);
                        this.redis.removeAllSessionState(this.clientId);
                    }
                }
            }
        }
    } catch (InterruptedException e) {
        logger.error("Lock error: Interrupted when trying to lock on client {}: ", this.clientId, e);
    } finally {
        // Always unlock
        lock.unlock();
    }

    // ============================== LOCK LOCK LOCK ==============================

    return redirect;
}
 
開發者ID:12315jack,項目名稱:j1st-mqtt,代碼行數:54,代碼來源:SyncRedisHandler.java

示例11: tryLock

import java.util.concurrent.locks.Lock; //導入方法依賴的package包/類
public boolean tryLock(String lockKey) {
    Lock lock = getLock(lockKey);
    return lock.tryLock();
}
 
開發者ID:alibaba,項目名稱:Dragonfly,代碼行數:5,代碼來源:LockService.java

示例12: getDistributedLockIfGlobal

import java.util.concurrent.locks.Lock; //導入方法依賴的package包/類
/**
 * If this region's scope is GLOBAL, get a distributed lock on the given key, and return the Lock.
 * The sender is responsible for unlocking.
 * 
 * @return the acquired Lock if the region is GLOBAL, otherwise null.
 * 
 * @throws NullPointerException if key is null
 */
private Lock getDistributedLockIfGlobal(Object key) throws TimeoutException {
  if (getScope().isGlobal()) {
    if (isLockingSuspendedByCurrentThread())
      return null;
    long start = System.currentTimeMillis();
    long timeLeft = getCache().getLockTimeout();
    long lockTimeout = timeLeft;
    StringId msg = null;
    Object[] msgArgs = null;
    while (timeLeft > 0 || lockTimeout == -1) {
      this.cache.getCancelCriterion().checkCancelInProgress(null);
      boolean interrupted = Thread.interrupted();
      try {
        Lock dlock = getDistributedLock(key);
        if (!dlock.tryLock(timeLeft, TimeUnit.SECONDS)) {
          msg =
              LocalizedStrings.DistributedRegion_ATTEMPT_TO_ACQUIRE_DISTRIBUTED_LOCK_FOR_0_FAILED_AFTER_WAITING_1_SECONDS;
          msgArgs =
              new Object[] {key, Long.valueOf((System.currentTimeMillis() - start) / 1000L)};
          break;
        }

        return dlock;
      } catch (InterruptedException ex) {
        interrupted = true;
        this.cache.getCancelCriterion().checkCancelInProgress(ex);
        // FIXME Why is it OK to keep going?
        if (lockTimeout > -1) {
          timeLeft = getCache().getLockTimeout() - ((System.currentTimeMillis() - start) / 1000L);
        }
      } finally {
        if (interrupted) {
          Thread.currentThread().interrupt();
        }
      }
    } // while
    if (msg == null) {
      msg =
          LocalizedStrings.DistributedRegion_TIMED_OUT_AFTER_WAITING_0_SECONDS_FOR_THE_DISTRIBUTED_LOCK_FOR_1;
      msgArgs = new Object[] {Integer.valueOf(getCache().getLockTimeout()), key};
    }
    throw new TimeoutException(msg.toLocalizedString(msgArgs));
  } else {
    return null;
  }
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:55,代碼來源:DistributedRegion.java

示例13: testSyncDeadlock

import java.util.concurrent.locks.Lock; //導入方法依賴的package包/類
/**
 * Make sure that we can detect a deadlock between two threads that are trying to acquire a two
 * different syncs in the different orders.
 */
@Test
public void testSyncDeadlock() throws Exception {
  final Lock lock1 = new ReentrantLock();
  final Lock lock2 = new ReentrantLock();

  Thread thread1 = new Thread() {
    public void run() {
      stuckThreads.add(Thread.currentThread());

      lock1.lock();

      Thread thread2 = new Thread() {
        public void run() {
          stuckThreads.add(Thread.currentThread());
          lock2.lock();
          try {
            lock1.tryLock(10, TimeUnit.SECONDS);
          } catch (InterruptedException e) {
            // ignore
          }
          lock2.unlock();
        }
      };

      thread2.start();

      try {
        Thread.sleep(1000);
        lock2.tryLock(10, TimeUnit.SECONDS);
      } catch (InterruptedException ignore) {
      }

      lock1.unlock();
    }
  };

  thread1.start();

  Thread.sleep(2000);

  DeadlockDetector detector = new DeadlockDetector();
  detector.addDependencies(DeadlockDetector.collectAllDependencies("here"));
  LinkedList<Dependency> deadlocks = detector.findDeadlock();

  System.out.println("deadlocks=" + DeadlockDetector.prettyFormat(deadlocks));

  assertEquals(4, detector.findDeadlock().size());
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:53,代碼來源:DeadlockDetectorIntegrationTest.java


注:本文中的java.util.concurrent.locks.Lock.tryLock方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。