Java 类java.util.concurrent.locks.Lock 实例源码

项目:jsf-sdk    文件:LockUtil.java   
/**
 * 锁
 *
 * @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;
    }
}
项目:lams    文件:ObligationService.java   
/**
 * Processes the obligations within the effective XACML policy.
 * 
 * This method waits until a read lock is obtained for the set of registered obligation handlers.
 * 
 * @param context current processing context
 * 
 * @throws ObligationProcessingException thrown if there is a problem evaluating an obligation
 */
public void processObligations(ObligationProcessingContext context) throws ObligationProcessingException {
    Lock readLock = rwLock.readLock();
    readLock.lock();
    try {
        Iterator<BaseObligationHandler> handlerItr = obligationHandlers.iterator();
        Map<String, ObligationType> effectiveObligations = preprocessObligations(context);

        BaseObligationHandler handler;
        while (handlerItr.hasNext()) {
            handler = handlerItr.next();
            if (effectiveObligations.containsKey(handler.getObligationId())) {
                handler.evaluateObligation(context, effectiveObligations.get(handler.getObligationId()));
            }
        }
    } finally {
        readLock.unlock();
    }
}
项目:server    文件:PeerRegistry.java   
int count(Predicate<PeerInfo> predicate) {

        int numberOfConnectedPeers = 0;

        Lock lock = readWriteLock.readLock();
        try {
            lock.lock();

            for (PeerInfo peer : peers.values()) {
                if (predicate.test(peer)) {
                    numberOfConnectedPeers++;
                }
            }

        } finally {
            lock.unlock();
        }

        return numberOfConnectedPeers;

    }
项目:unitimes    文件:TimetableSolver.java   
@Override
public Vector getChangesToInitial() {
    Vector ret = new Vector();
    Lock lock = currentSolution().getLock().readLock();
    lock.lock();
    try {
        for (Lecture lecture: currentSolution().getModel().variables()) {
            if (!ToolBox.equals(lecture.getInitialAssignment(),currentSolution().getAssignment().getValue(lecture))) {
                RecordedAssignment a = new RecordedAssignment(this,(Placement)lecture.getInitialAssignment(),currentSolution().getAssignment().getValue(lecture)); 
                if (lecture.getInitialAssignment()!=null) {
                    a.getBefore().setDetails(new ClassAssignmentDetails(this,lecture,(Placement)lecture.getInitialAssignment(),false));
                }
                if (currentSolution().getAssignment().getValue(lecture)!=null) {
                    a.getAfter().setDetails(new ClassAssignmentDetails(this,lecture,false));
                }
                ret.addElement(a);
            }
        }
    } finally {
        lock.unlock();
    }
    return ret;
}
项目:lams    文件:IndexingObjectStore.java   
/**
 * Gets a registered object by its index.
 * 
 * @param index the index of an object previously registered, may be null
 * 
 * @return the registered object or null if no object is registered for that index
 */
public T get(String index) {
    if (index == null) {
        return null;
    }

    Lock readLock = rwLock.readLock();
    readLock.lock();
    try {
        StoredObjectWrapper objectWrapper = objectStore.get(index);
        if (objectWrapper != null) {
            return objectWrapper.getObject();
        }

        return null;
    } finally {
        readLock.unlock();
    }
}
项目:apache-tomcat-7.0.73-with-comment    文件:ContainerBase.java   
/**
 * Return the Realm with which this Container is associated.  If there is
 * no associated Realm, return the Realm associated with our parent
 * Container (if any); otherwise return <code>null</code>.
 */
@Override
public Realm getRealm() {

    Lock l = realmLock.readLock();
    try {
        l.lock();
        if (realm != null)
            return (realm);
        if (parent != null)
            return (parent.getRealm());
        return null;
    } finally {
        l.unlock();
    }
}
项目:monarch    文件:DistributedRegion.java   
@Override
public Lock getDistributedLock(Object key) throws IllegalStateException {
  validateKey(key);
  lockCheckReadiness();
  checkForLimitedOrNoAccess();
  if (!this.scope.isGlobal()) {
    throw new IllegalStateException(
        LocalizedStrings.DistributedRegion_DISTRIBUTION_LOCKS_ARE_ONLY_SUPPORTED_FOR_REGIONS_WITH_GLOBAL_SCOPE_NOT_0
            .toLocalizedString(this.scope));
  }
  if (isLockingSuspendedByCurrentThread()) {
    throw new IllegalStateException(
        LocalizedStrings.DistributedRegion_THIS_THREAD_HAS_SUSPENDED_ALL_LOCKING_FOR_THIS_REGION
            .toLocalizedString());
  }
  return new DistributedLock(key);
}
项目:springboot-shiro-cas-mybatis    文件:HazelcastTicketRegistry.java   
@Override
public Collection<Ticket> getTickets() {
    final Collection<Ticket> collection = new HashSet<>();

    final Lock lock = this.hz.getLock(getClass().getName());
    lock.lock();
    try {
        final PagingPredicate pagingPredicate = new PagingPredicate(this.pageSize);
        for (Collection<Ticket> entrySet = this.registry.values(pagingPredicate);
             !entrySet.isEmpty();
             pagingPredicate.nextPage(), entrySet = this.registry.values(pagingPredicate)) {
            for (final Ticket entry : entrySet) {
                collection.add(decodeTicket(entry));
            }
        }
    } finally {
        lock.unlock();
    }
    return collection;
}
项目:lams    文件:IndexingObjectStore.java   
/**
 * Adds the given object to the store. Technically this method only adds the object if it does not already exist in
 * the store. If it does this method simply increments the reference count of the object.
 * 
 * @param object the object to add to the store, may be null
 * 
 * @return the index that may be used to later retrieve the object or null if the object was null
 */
public String put(T object) {
    if (object == null) {
        return null;
    }

    Lock writeLock = rwLock.writeLock();
    writeLock.lock();
    try {
        String index = Integer.toString(object.hashCode());

        StoredObjectWrapper objectWrapper = objectStore.get(index);
        if (objectWrapper == null) {
            objectWrapper = new StoredObjectWrapper(object);
            objectStore.put(index, objectWrapper);
        }
        objectWrapper.incremementReferenceCount();

        return index;
    } finally {
        writeLock.unlock();
    }
}
项目:openjdk-jdk10    文件:StampedLockTest.java   
/**
 * asReadLock can be locked and unlocked
 */
public void testAsReadLock() throws Throwable {
    StampedLock sl = new StampedLock();
    Lock lock = sl.asReadLock();
    for (Action locker : lockLockers(lock)) {
        locker.run();
        assertTrue(sl.isReadLocked());
        assertFalse(sl.isWriteLocked());
        assertEquals(1, sl.getReadLockCount());
        locker.run();
        assertTrue(sl.isReadLocked());
        assertEquals(2, sl.getReadLockCount());
        lock.unlock();
        lock.unlock();
        assertUnlocked(sl);
    }
}
项目:unitimes    文件:TimetableSolver.java   
@Override
public Vector getChangesToBest() {
    Vector ret = new Vector();
    Lock lock = currentSolution().getLock().readLock();
    lock.lock();
    try {
        for (Lecture lecture: currentSolution().getModel().variables()) {
            Placement placement = currentSolution().getAssignment().getValue(lecture);
            if (!ToolBox.equals(lecture.getBestAssignment(), placement)) {
                RecordedAssignment a = new RecordedAssignment(this,(Placement)lecture.getBestAssignment(),placement);
                if (lecture.getBestAssignment()!=null) {
                    a.getBefore().setDetails(new ClassAssignmentDetails(this,lecture,(Placement)lecture.getBestAssignment(),false));
                }
                if (placement!=null) {
                    a.getAfter().setDetails(new ClassAssignmentDetails(this,lecture,false));
                }
                ret.addElement(a);
            }
        }
    } finally {
        lock.unlock();
    }
    return ret;
}
项目:hadoop    文件:CleanerTask.java   
/**
 * Creates a cleaner task based on the configuration. This is provided for
 * convenience.
 *
 * @param conf
 * @param store
 * @param metrics
 * @param cleanerTaskLock lock that ensures a serial execution of cleaner
 *                        task
 * @return an instance of a CleanerTask
 */
public static CleanerTask create(Configuration conf, SCMStore store,
    CleanerMetrics metrics, Lock cleanerTaskLock) {
  try {
    // get the root directory for the shared cache
    String location =
        conf.get(YarnConfiguration.SHARED_CACHE_ROOT,
            YarnConfiguration.DEFAULT_SHARED_CACHE_ROOT);

    long sleepTime =
        conf.getLong(YarnConfiguration.SCM_CLEANER_RESOURCE_SLEEP_MS,
            YarnConfiguration.DEFAULT_SCM_CLEANER_RESOURCE_SLEEP_MS);
    int nestedLevel = SharedCacheUtil.getCacheDepth(conf);
    FileSystem fs = FileSystem.get(conf);

    return new CleanerTask(location, sleepTime, nestedLevel, fs, store,
        metrics, cleanerTaskLock);
  } catch (IOException e) {
    LOG.error("Unable to obtain the filesystem for the cleaner service", e);
    throw new ExceptionInInitializerError(e);
  }
}
项目:Lucid2.0    文件:NPCScriptManager.java   
public final void action(final MapleClient c, final byte mode, final byte type, final int selection) {
    if (mode != -1) {
        final NPCConversationManager cm = cms.get(c);
        if (cm == null || cm.getLastMsg() > -1) {
            return;
        }
        final Lock lock = c.getNPCLock();
        lock.lock();
        try {
            if (cm.pendingDisposal) {
                dispose(c);
            } else {
                c.setClickedNPC();
                cm.getIv().invokeFunction("action", mode, type, selection);
            }
        } catch (final ScriptException | NoSuchMethodException e) {
            System.err.println("Error executing NPC script. NPC ID : " + cm.getNpc() + ":" + e);
            dispose(c);
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
项目:unitimes    文件:TimetableSolver.java   
@Override
  public AssignmentPreferenceInfo getAssignmentInfo(Long classId) {
    Lock lock = currentSolution().getLock().readLock();
lock.lock();
try {
        Lecture lecture = null;
        for (Lecture l: currentSolution().getModel().variables()) {
            if (l.getClassId().equals(classId)) {
                lecture = l; break;
            }
        }
        if (lecture==null) return null;
        Placement placement = (Placement)currentSolution().getAssignment().getValue(lecture);
        if (placement==null) return null;
        return new AssignmentPreferenceInfo(this,placement);
    } finally {
        lock.unlock();
    }
  }
项目:gitplex-mit    文件:DefaultAvatarManager.java   
private String generateAvatar(String primaryName, String secondaryName) {
    String encoded = Hex.encodeHexString((primaryName + ":" + AvatarGenerator.version()).getBytes());

    if (StringUtils.isBlank(primaryName))
        primaryName = "?";
    if (StringUtils.isBlank(secondaryName))
        secondaryName = primaryName;

    File avatarFile = new File(Bootstrap.getSiteDir(), "avatars/generated/" + encoded);
    if (!avatarFile.exists()) {
        Lock avatarLock = LockUtils.getLock("generated-avatar:" + encoded);
        avatarLock.lock();
        try {
            String letters = getLetter(primaryName);
            BufferedImage bi = AvatarGenerator.generate(letters, secondaryName);
            FileUtils.createDir(avatarFile.getParentFile());
            ImageIO.write(bi, "PNG", avatarFile);
        } catch (NoSuchAlgorithmException | IOException e) {
            throw new RuntimeException(e);
        } finally {
            avatarLock.unlock();
        }
    }

    return AVATARS_BASE_URL + "generated/" + encoded;
}
项目:dibd    文件:StorageObjectPool.java   
@Override
public ArticleForPush createReplayWeb(ArticleWebInput article, File file)
        throws StorageBackendException {
    StorageWeb db = null;
    Lock l = locks[2];
    l.lock();
    try{
        db = fixedStoragePool.remove();
        ArticleForPush ret = db.createReplayWeb(article, file);
        return ret;
    }finally{
        if( db != null)
            fixedStoragePool.add(db);
        l.unlock();
    }
}
项目:alfresco-core    文件:LockHelper.java   
/**
 * 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.");
    }
}
项目:lams    文件:ChainingMetadataProvider.java   
/** {@inheritDoc} */
public EntitiesDescriptor getEntitiesDescriptor(String name) throws MetadataProviderException {
    Lock readLock = providerLock.readLock();
    readLock.lock();

    EntitiesDescriptor descriptor = null;
    try {
        for (MetadataProvider provider : providers) {
            log.debug("Checking child metadata provider for entities descriptor with name: {}", name);
            try {
                descriptor = provider.getEntitiesDescriptor(name);
                if (descriptor != null) {
                    break;
                }
            } catch (MetadataProviderException e) {
                log.warn("Error retrieving metadata from provider of type {}, proceeding to next provider",
                        provider.getClass().getName(), e);
                continue;
            }
        }
    } finally {
        readLock.unlock();
    }

    return descriptor;
}
项目:businessworks    文件:CycleDetectingLock.java   
ReentrantCycleDetectingLock(CycleDetectingLockFactory<ID> lockFactory,
    ID userLockId, Lock lockImplementation) {
  this.lockFactory = lockFactory;
  this.userLockId = Preconditions.checkNotNull(userLockId, "userLockId");
  this.lockImplementation = Preconditions.checkNotNull(
      lockImplementation, "lockImplementation");
}
项目:monarch    文件:GlobalLockingDUnitTest.java   
/**
 * Test Region.getRegionDistributedLock(), calling lock() and then unlock()
 */
@Test
public void testRegionDistributedLockSimple() throws CacheException {
  final String name = this.getUniqueName();
  Region r = getOrCreateRootRegion().createSubregion(name, getGlobalAttrs());
  Lock lock = r.getRegionDistributedLock();
  lock.lock();
  lock.unlock();
}
项目:monarch    文件:LocalRegion.java   
/**
 * This implementation only checks readiness and scope
 */
public Lock getDistributedLock(Object key) throws IllegalStateException {
  checkReadiness();
  checkForLimitedOrNoAccess();
  Scope theScope = getAttributes().getScope();
  Assert.assertTrue(theScope == Scope.LOCAL);
  throw new IllegalStateException(
      LocalizedStrings.LocalRegion_ONLY_SUPPORTED_FOR_GLOBAL_SCOPE_NOT_LOCAL.toLocalizedString());
}
项目:tomcat7    文件:ManagedBean.java   
public void setDescription(String description) {
    Lock l = mBeanInfoLock.writeLock();
    l.lock();
    try {
        this.description = description;
        this.info = null;
    } finally {
        l.unlock();
    }
}
项目:Reer    文件:LockOnDemandCrossProcessCacheAccess.java   
/**
 * Actions are notified when lock is opened or closed. Actions are called while holding state lock, so that no other threads are working with cache while these are running.
 *
 * @param stateLock Lock to hold while mutating state.
 * @param onOpen Action to run when the lock is opened. Action is called while holding state lock
 * @param onClose Action to run when the lock is closed. Action is called while holding state lock
 */
public LockOnDemandCrossProcessCacheAccess(String cacheDisplayName, File lockTarget, LockOptions lockOptions, FileLockManager lockManager, Lock stateLock, CacheInitializationAction initAction, Action<FileLock> onOpen, Action<FileLock> onClose) {
    this.cacheDisplayName = cacheDisplayName;
    this.lockTarget = lockTarget;
    this.lockOptions = lockOptions;
    this.lockManager = lockManager;
    this.stateLock = stateLock;
    this.initAction = initAction;
    this.onOpen = onOpen;
    this.onClose = onClose;
}
项目:apache-tomcat-7.0.73-with-comment    文件:OperationInfo.java   
/**
 * Add a new parameter to the set of arguments for this operation.
 *
 * @param parameter The new parameter descriptor
 */
public void addParameter(ParameterInfo parameter) {

    Lock writeLock = parametersLock.writeLock();
    try {
        writeLock.lock();
        ParameterInfo results[] = new ParameterInfo[parameters.length + 1];
        System.arraycopy(parameters, 0, results, 0, parameters.length);
        results[parameters.length] = parameter;
        parameters = results;
        this.info = null;
    } finally {
        writeLock.unlock();
    }
}
项目:Elasticsearch    文件:ReleasableLock.java   
public ReleasableLock(Lock lock) {
    this.lock = lock;
    boolean useHoldingThreads = false;
    assert (useHoldingThreads = true);
    if (useHoldingThreads) {
        holdingThreads = new ThreadLocal<>();
    } else {
        holdingThreads = null;
    }
}
项目:waggle-dance    文件:MetaStoreProxyServer.java   
private void signalOtherThreadsToStart(
    final TServer server,
    final Lock startLock,
    final Condition startCondition,
    final AtomicBoolean startedServing) {
  // A simple thread to wait until the server has started and then signal the other threads to
  // begin
  Thread t = new Thread() {
    @Override
    public void run() {
      do {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          LOG.warn("Signalling thread was interuppted: " + e.getMessage());
        }
      } while (!server.isServing());
      startLock.lock();
      try {
        startedServing.set(true);
        startCondition.signalAll();
      } finally {
        startLock.unlock();
      }
    }
  };
  t.start();
}
项目:unitimes    文件:InstructorSchedulingSolver.java   
@Override
public SuggestionsResponse computeSuggestions(ComputeSuggestionsRequest request) {
       Lock lock = currentSolution().getLock().readLock();
       lock.lock();
       try {
        return new InstructorSchedulingSuggestions(this).computeSuggestions(request);
       } finally {
        lock.unlock();
       }
}
项目:nexus-blobstore-s3    文件:S3BlobStore.java   
@Nullable
@Override
public Blob get(final BlobId blobId, final boolean includeDeleted) {
  checkNotNull(blobId);

  final S3Blob blob = liveBlobs.getUnchecked(blobId);

  if (blob.isStale()) {
    Lock lock = blob.lock();
    try {
      if (blob.isStale()) {
        S3BlobAttributes blobAttributes = new S3BlobAttributes(s3, getConfiguredBucket(), attributePath(blobId).toString());
        boolean loaded = blobAttributes.load();
        if (!loaded) {
          log.warn("Attempt to access non-existent blob {} ({})", blobId, blobAttributes);
          return null;
        }

        if (blobAttributes.isDeleted() && !includeDeleted) {
          log.warn("Attempt to access soft-deleted blob {} ({})", blobId, blobAttributes);
          return null;
        }

        blob.refresh(blobAttributes.getHeaders(), blobAttributes.getMetrics());
      }
    }
    catch (IOException e) {
      throw new BlobStoreException(e, blobId);
    }
    finally {
      lock.unlock();
    }
  }

  log.debug("Accessing blob {}", blobId);

  return blob;
}
项目:dlock    文件:DLockGenerator.java   
/**
 * Get lock with a default lease time configured in the config-dlock.properties
 *
 * @param lockType enum DLockType
 * @param lockTarget
 * @return
 */
public Lock gen(DLockType lockType, String lockTarget) {
    // pre-check
    Integer lease = lockConfigMap.get(lockType);
    Assert.notNull(lease, "unfound config for DLockType:" + lockType);

    return getLockInstance(lockType.name(), lockTarget, lease, TimeUnit.MILLISECONDS);
}
项目:incubator-netbeans    文件:ClassIndexManagerTest.java   
public void testDeadLock207855() throws Exception {
    clearWorkDir();
    final File wd = getWorkDir();
    final File cache = new File (wd,"cache");   //NOI18N
    cache.mkdir();
    IndexUtil.setCacheFolder(cache);
    final File root = new File (wd,"src");      //NOI18N
    root.mkdir();
    final Lock lock = new ReentrantLock();
    final CountDownLatch holdsLock = new CountDownLatch(1);
    final CountDownLatch inListener = new CountDownLatch(1);
    final FileChangeListener dl = new DeadLockListener(lock, inListener);
    FileUtil.addRecursiveListener(dl, cache);
    try {
        final Thread worker = new Thread() {
            @Override
            public void run() {
                lock.lock();
                holdsLock.countDown();
                try {
                    inListener.await();
                    ClassIndexManager.getDefault().getUsagesQuery(Utilities.toURI(root).toURL(), true);
                } catch (InterruptedException ie) {
                    Exceptions.printStackTrace(ie);
                } catch (MalformedURLException ex) {
                    Exceptions.printStackTrace(ex);
                } finally {
                    lock.unlock();
                }
            }
        };
        worker.start();
        holdsLock.await();
        ClassIndexManager.getDefault().getUsagesQuery(Utilities.toURI(root).toURL(), true);
    } finally {
        FileUtil.removeRecursiveListener(dl, cache);
    }
}
项目:unitimes    文件:TimetableSolver.java   
@Override
  public AssignmentPreferenceInfo getInfo(Hint hint) {
    Lock lock = currentSolution().getLock().readLock();
lock.lock();
try {
        return hint.getInfo(this);
    } finally {
        lock.unlock();
    }
  }
项目:ditb    文件:HRegion.java   
private RowLockImpl getRowLock(Lock l) {
  count.incrementAndGet();
  synchronized (lock) {
    if (usable.get()) {
      return new RowLockImpl(this, l);
    } else {
      return null;
    }
  }
}
项目:java-monitoring-client-library    文件:Counter.java   
@VisibleForTesting
void incrementBy(long offset, Instant startTimestamp, ImmutableList<String> labelValues) {
  Lock lock = valueLocks.get(labelValues);
  lock.lock();

  try {
    values.addAndGet(labelValues, offset);
    valueStartTimestamps.putIfAbsent(labelValues, startTimestamp);
  } finally {
    lock.unlock();
  }
}
项目:dibd    文件:StorageObjectPool.java   
@Override
public ArticleOutput getArticleWeb(String message_id, Integer id) throws StorageBackendException {
    StorageWeb db = null;
    Lock l = locks[0];
    l.lock();
    try{
        db = fixedStoragePool.remove();
        ArticleOutput ret = db.getArticleWeb(message_id, id);
        return ret;
    }finally{
        if( db != null)
            fixedStoragePool.add(db);
        l.unlock();
    }
}
项目:tomcat7    文件:ManagedBean.java   
public void setType(String type) {
    Lock l = mBeanInfoLock.writeLock();
    l.lock();
    try {
        this.type = type;
        this.info = null;
    } finally {
        l.unlock();
    }
}
项目:java-monitoring-client-library    文件:EventMetric.java   
@VisibleForTesting
final void reset(Instant startTimestamp, ImmutableList<String> labelValues) {
  Lock lock = valueLocks.get(labelValues);
  lock.lock();

  try {
    this.values.put(labelValues, new MutableDistribution(distributionFitter));
    this.valueStartTimestamps.put(labelValues, startTimestamp);
  } finally {
    lock.unlock();
  }
}
项目:monarch    文件:BucketAdvisor.java   
/**
 * Returns the lock that prevents the parent's primary from moving while active writes are in
 * progress. This should be locked before checking if the local bucket is primary.
 * 
 * @return the lock for in-progress write operations
 */
Lock getParentActiveWriteLock() {
  if (this.parentAdvisor != null) {
    return this.parentAdvisor.getActiveWriteLock();
  }
  return null;
}
项目:lams    文件:ObligationService.java   
/**
 * Adds a collection of obligation handler to the list of registered handlers
 * 
 * This method waits until a write lock is obtained for the set of registered obligation handlers.
 * 
 * @param handlers the collection of handlers to add to the list of registered handlers.
 */
public void addObligationhandler(Collection<BaseObligationHandler> handlers) {
    if (handlers == null || handlers.isEmpty()) {
        return;
    }

    Lock writeLock = rwLock.writeLock();
    writeLock.lock();
    try {
        obligationHandlers.addAll(handlers);
    } finally {
        writeLock.unlock();
    }
}
项目:monarch    文件:ConcurrentRowTuplePutGetJUnitTest.java   
void get() {
  int randomInt1 = random.nextInt() % 10;
  if (randomInt1 < 0) {
    randomInt1 = randomInt1 * (-1);
  }

  Integer integer1 = Integer.valueOf(randomInt1);
  Object v = null;
  Object expected = null;
  Lock lock = null;
  if (this.validate) {
    lock = map.get(integer1);
    lock.lock();
  }
  try {
    try {
      logWriter.info("Key = " + integer1.longValue());
      v = region1.get(integer1);
      if (this.validate) {
        expected = region2.get(integer1);
      }
    } catch (Exception e) {
      e.printStackTrace();
      exceptionOccuredInGets = true;
      logWriter.severe("Exception occured in get ", e);
      fail(" failed during get due to " + e);
    }
  } finally {
    if (lock != null) {
      lock.unlock();
    }
  }
  if (this.validate) {
    assertEquals(expected, v);
  }
}
项目:unitimes    文件:AbstractSolver.java   
@Override
protected void onFinish() {
    super.onFinish();
    try {
        iWorking = true;
        if (currentSolution().getBestInfo()!=null)
            currentSolution().restoreBest();
        finishBeforeSave();
        if (currentSolution().getBestInfo()!=null && getProperties().getPropertyBoolean("General.Save",false)) {
            ProblemSaver<V, T, M> saver = getDatabaseSaver(this);
            Lock lock = currentSolution().getLock().readLock();
            lock.lock();
            try {
                saver.save();
            } catch (Exception e) {
                sLog.error("Failed to save the problem: " + e.getMessage(), e);
            } finally {
                lock.unlock();
            }
        }
        if (getProperties().getPropertyBoolean("General.Unload",false)) {
            dispose();
        } else {
            Progress.getInstance(currentSolution().getModel()).setStatus("Awaiting commands ...");
        }
    } finally {
        iWorking = false;
    }
}