当前位置: 首页>>代码示例>>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;未经允许,请勿转载。