Example usage for java.util.concurrent.locks Lock unlock

List of usage examples for java.util.concurrent.locks Lock unlock

Introduction

In this page you can find the example usage for java.util.concurrent.locks Lock unlock.

Prototype

void unlock();

Source Link

Document

Releases the lock.

Usage

From source file:com.netprogs.minecraft.plugins.social.SocialPerson.java

public void breakEngagement() {
    Lock lock = rwEngagementLock.writeLock();
    lock.lock();/*from w  w w . j a  v  a2  s. c om*/
    try {

        String engagementName = StringUtils.EMPTY;
        if (person.getEngagement() != null) {
            engagementName = person.getEngagement().getPlayerName();
            firePlayerMemberChangeEvent(engagementName, SocialNetworkCommandType.engagement, Type.preRemove,
                    true);
        }

        person.setEngagement(null);
        socialEngagement = null;

        if (StringUtils.isNotEmpty(engagementName)) {
            firePlayerMemberChangeEvent(engagementName, SocialNetworkCommandType.engagement, Type.postRemove,
                    true);
        }
    } finally {
        lock.unlock();
    }
}

From source file:org.opendedup.collections.ProgressiveFileBasedCSMap.java

private AbstractShard getReadMap(byte[] hash) throws IOException {
    Lock l = gcLock.readLock();
    l.lock();//from ww  w. j  a v a2 s .c  om
    // ct.incrementAndGet();
    try {

        if (!runningGC && !lbf.mightContain(hash)) {
            // SDFSLogger.getLog().info("not in bloom filter");
            return null;
        }

        /*
         * Iterator<ProgressiveFileByteArrayLongMap> iter =
         * activeReadMaps.iterator(); while (iter.hasNext()) {
         * ProgressiveFileByteArrayLongMap _m = iter.next(); if
         * (_m.containsKey(hash)) return _m; }
         */
        // zmt.incrementAndGet();
        /*
         * synchronized (ct) { if (ct.get() > 10000) {
         * SDFSLogger.getLog().info( "misses=" + mt.get() + " attempts=" +
         * ct.get() + " lookups=" + amt.get()); ct.set(0); amt.set(0);
         * mt.set(0); } }
         */
        for (AbstractShard _m : this.maps.getAL()) {
            // amt.incrementAndGet();
            try {
                if (_m.containsKey(hash)) {
                    if (runningGC)
                        this.lbf.put(hash);
                    return _m;
                }
            } catch (MapClosedException e) {
                this.getReadMap(hash);
            }
        }
        // mt.incrementAndGet();

        return null;

    } finally {
        l.unlock();
    }

}

From source file:net.myrrix.online.ServerRecommender.java

/**
 * Computes items most similar to an item or items. The returned items have the highest average similarity
 * to the given items./*from  ww  w.j  av a2 s. c o m*/
 *
 * @param itemIDs items for which most similar items are required
 * @param howMany maximum number of similar items to return; fewer may be returned
 * @param rescorer rescoring function used to modify item-item similarities before ranking results
 * @return {@link RecommendedItem}s representing the top recommendations for the user, ordered by quality,
 *  descending. The score associated to it is an opaque value. Larger means more similar, but no further
 *  interpretation may necessarily be applied.
 * @throws NoSuchItemException if any of the items is not known in the model
 * @throws NotReadyException if the recommender has no model available yet
 */
@Override
public List<RecommendedItem> mostSimilarItems(long[] itemIDs, int howMany, Rescorer<LongPair> rescorer)
        throws NoSuchItemException, NotReadyException {

    Preconditions.checkArgument(howMany > 0, "howMany must be positive");

    Generation generation = getCurrentGeneration();
    FastByIDMap<float[]> Y = generation.getY();

    Lock yLock = generation.getYLock().readLock();
    yLock.lock();
    try {

        List<float[]> itemFeatures = Lists.newArrayListWithCapacity(itemIDs.length);
        for (long itemID : itemIDs) {
            float[] features = Y.get(itemID);
            if (features != null) {
                itemFeatures.add(features);
            }
        }
        if (itemFeatures.isEmpty()) {
            throw new NoSuchItemException(Arrays.toString(itemIDs));
        }
        float[][] itemFeaturesArray = itemFeatures.toArray(new float[itemFeatures.size()][]);

        return TopN.selectTopN(new MostSimilarItemIterator(Y.entrySet().iterator(), generation.getUserTagIDs(),
                itemIDs, itemFeaturesArray, rescorer), howMany);
    } finally {
        yLock.unlock();
    }
}

From source file:net.myrrix.online.ServerRecommender.java

@Override
public List<RecommendedItem> mostPopularItems(int howMany, IDRescorer rescorer) throws NotReadyException {

    Preconditions.checkArgument(howMany > 0, "howMany must be positive");

    Generation generation = getCurrentGeneration();
    FastByIDMap<FastIDSet> knownItemIDs = generation.getKnownItemIDs();
    if (knownItemIDs == null) {
        throw new UnsupportedOperationException();
    }//  w w  w  .  j  av a2 s .  c om

    FastIDSet itemTagIDs = generation.getItemTagIDs();
    FastByIDFloatMap itemCounts = new FastByIDFloatMap();
    Lock knownItemReadLock = generation.getKnownItemLock().readLock();
    knownItemReadLock.lock();
    try {
        // Don't count data from users that are really item tags
        Lock xReadLock = generation.getXLock().readLock();
        xReadLock.lock();
        try {

            for (FastByIDMap.MapEntry<FastIDSet> entry : generation.getKnownItemIDs().entrySet()) {
                long userID = entry.getKey();
                if (!itemTagIDs.contains(userID)) {
                    FastIDSet itemIDs = entry.getValue();
                    synchronized (itemIDs) {
                        LongPrimitiveIterator it = itemIDs.iterator();
                        while (it.hasNext()) {
                            long itemID = it.nextLong();
                            itemCounts.increment(itemID, 1.0f);
                        }
                    }
                }
            }

        } finally {
            xReadLock.unlock();
        }
    } finally {
        knownItemReadLock.unlock();
    }

    // Filter out 'items' that were really user tags
    FastIDSet userTagIDs = generation.getUserTagIDs();
    Lock yReadLock = generation.getYLock().readLock();
    yReadLock.lock();
    try {
        LongPrimitiveIterator it = itemCounts.keySetIterator();
        while (it.hasNext()) {
            if (userTagIDs.contains(it.nextLong())) {
                it.remove();
            }
        }
    } finally {
        yReadLock.unlock();
    }

    return TopN.selectTopN(new MostPopularItemsIterator(itemCounts.entrySet().iterator(), rescorer), howMany);
}

From source file:jp.aegif.nemaki.cmis.service.impl.ObjectServiceImpl.java

@Override
public ObjectData getObject(CallContext callContext, String repositoryId, String objectId, String filter,
        Boolean includeAllowableActions, IncludeRelationships includeRelationships, String renditionFilter,
        Boolean includePolicyIds, Boolean includeAcl, ExtensionsData extension) {

    exceptionService.invalidArgumentRequired("objectId", objectId);

    Lock lock = threadLockService.getReadLock(repositoryId, objectId);
    try {/*from w w w  .  j a va 2s  . co  m*/
        lock.lock();

        // //////////////////
        // General Exception
        // //////////////////
        Content content = contentService.getContent(repositoryId, objectId);
        // WORK AROUND: getObject(versionSeriesId) is interpreted as
        // getDocumentOflatestVersion
        if (content == null) {
            VersionSeries versionSeries = contentService.getVersionSeries(repositoryId, objectId);
            if (versionSeries != null) {
                content = contentService.getDocumentOfLatestVersion(repositoryId, objectId);
            }
        }
        exceptionService.objectNotFound(DomainType.OBJECT, content, objectId);
        exceptionService.permissionDenied(callContext, repositoryId,
                PermissionMapping.CAN_GET_PROPERTIES_OBJECT, content);

        // //////////////////
        // Body of the method
        // //////////////////
        ObjectData object = compileService.compileObjectData(callContext, repositoryId, content, filter,
                includeAllowableActions, includeRelationships, null, includeAcl);

        return object;
    } finally {
        lock.unlock();
    }
}

From source file:org.opendedup.collections.ShardedProgressiveFileBasedCSMap.java

private long getPos(byte[] hash) throws IOException {
    long pos = -1;
    Lock l = gcLock.readLock();
    l.lock();//from   ww w.  j a  v a  2s .  c  o  m
    try {
        if (!runningGC && !lbf.mightContain(hash)) {
            return pos;
        }
        AbstractShard k = this.keyLookup.getIfPresent(new ByteArrayWrapper(hash));
        if (k != null) {
            try {
                pos = k.get(hash);
                if (pos != -1) {

                    // m.cache();
                    return pos;
                } else {
                    this.keyLookup.invalidate(new ByteArrayWrapper(hash));
                }
            } catch (MapClosedException e) {
                this.keyLookup.invalidate(new ByteArrayWrapper(hash));
            }
        }

        for (AbstractShard m : this.maps.getAL()) {
            try {
                pos = m.get(hash);
                if (pos != -1) {

                    // m.cache();
                    return pos;
                }
            } catch (MapClosedException e) {
                this.keyLookup.invalidate(new ByteArrayWrapper(hash));
            }
        }
        return pos;
    } finally {
        l.unlock();
    }
}

From source file:edu.internet2.middleware.shibboleth.common.relyingparty.provider.SAMLMDRelyingPartyConfigurationManager.java

/** {@inheritDoc} */
public RelyingPartyConfiguration getRelyingPartyConfiguration(String relyingPartyEntityID) {
    Lock readLock = getReadWriteLock().readLock();
    readLock.lock();// w  w  w.j  a va 2 s  .c  o  m

    try {
        log.debug("Looking up relying party configuration for {}", relyingPartyEntityID);
        if (rpConfigs.containsKey(relyingPartyEntityID)) {
            log.debug("Custom relying party configuration found for {}", relyingPartyEntityID);
            return rpConfigs.get(relyingPartyEntityID);
        }

        log.debug(
                "No custom relying party configuration found for {}, looking up configuration based on metadata groups.",
                relyingPartyEntityID);
        try {
            if (metadataProvider == null) {
                log.debug(
                        "No metadata provider available, unable to lookup configuration based on entity group");
            } else {
                EntityDescriptor entityDescriptor = metadataProvider.getEntityDescriptor(relyingPartyEntityID);
                if (entityDescriptor != null) {
                    EntitiesDescriptor entityGroup = (EntitiesDescriptor) entityDescriptor.getParent();
                    while (entityGroup != null) {
                        if (rpConfigs.containsKey(entityGroup.getName())) {
                            log.debug("Relying party configuration found for {} as member of metadata group {}",
                                    relyingPartyEntityID, entityGroup.getName());
                            return rpConfigs.get(entityGroup.getName());
                        }
                        entityGroup = (EntitiesDescriptor) entityGroup.getParent();
                    }
                }
            }
        } catch (MetadataProviderException e) {
            log.error("Error fetching metadata for relying party " + relyingPartyEntityID, e);
        }

        log.debug(
                "No custom or group-based relying party configuration found for {}. Using default relying party configuration.",
                relyingPartyEntityID);
        return getDefaultRelyingPartyConfiguration();
    } finally {
        readLock.unlock();
    }
}

From source file:com.mirth.connect.donkey.server.channel.Channel.java

public void invalidateQueues() {
    sourceQueue.invalidate(true, false);

    for (DestinationChainProvider chainProvider : destinationChainProviders) {
        for (Integer metaDataId : chainProvider.getMetaDataIds()) {
            DestinationQueue queue = chainProvider.getDestinationConnectors().get(metaDataId).getQueue();

            /*// w  ww .  j  a  va2  s.  c om
             * Before invalidating first obtain a write lock from the queue. This is done so
             * that no queue threads can commit an updated status to the database while the
             * invalidation is happening.
             */
            Lock lock = queue.getInvalidationLock();
            lock.lock();
            try {
                queue.invalidate(true, false);
            } finally {
                lock.unlock();
            }
        }
    }
}

From source file:org.apache.bookkeeper.bookie.EntryLogManagerForEntryLogPerLedger.java

@Override
BufferedLogChannel getCurrentLogForLedgerForAddEntry(long ledgerId, int entrySize, boolean rollLog)
        throws IOException {
    Lock lock = getLock(ledgerId);
    lock.lock();/*  ww  w . j a v a  2  s. co m*/
    try {
        BufferedLogChannelWithDirInfo logChannelWithDirInfo = getCurrentLogWithDirInfoForLedger(ledgerId);
        BufferedLogChannel logChannel = null;
        if (logChannelWithDirInfo != null) {
            logChannel = logChannelWithDirInfo.getLogChannel();
        }
        boolean reachEntryLogLimit = rollLog ? reachEntryLogLimit(logChannel, entrySize)
                : readEntryLogHardLimit(logChannel, entrySize);
        // Create new log if logSizeLimit reached or current disk is full
        boolean diskFull = (logChannel == null) ? false : logChannelWithDirInfo.isLedgerDirFull();
        boolean allDisksFull = !ledgerDirsManager.hasWritableLedgerDirs();

        /**
         * if disk of the logChannel is full or if the entrylog limit is
         * reached of if the logchannel is not initialized, then
         * createNewLog. If allDisks are full then proceed with the current
         * logChannel, since Bookie must have turned to readonly mode and
         * the addEntry traffic would be from GC and it is ok to proceed in
         * this case.
         */
        if ((diskFull && (!allDisksFull)) || reachEntryLogLimit || (logChannel == null)) {
            if (logChannel != null) {
                logChannel.flushAndForceWriteIfRegularFlush(false);
            }
            createNewLog(ledgerId, ": diskFull = " + diskFull + ", allDisksFull = " + allDisksFull
                    + ", reachEntryLogLimit = " + reachEntryLogLimit + ", logChannel = " + logChannel);
        }

        return getCurrentLogForLedger(ledgerId);
    } finally {
        lock.unlock();
    }
}

From source file:com.netprogs.minecraft.plugins.social.SocialPerson.java

/**
 * Returns all the messages of the given type for the given player name.
 * This version allows us to not create a copy allowing us to work with it internally.
 * @param fromPlayerName/*  w  w w  .j a  v  a 2 s  . c o m*/
 * @param messageClass
 * @return
 */
@SuppressWarnings("unchecked")
private <U extends IMessage> List<U> getMessagesFrom(String fromPersonName, Class<U> messageClass,
        boolean createCopy) {

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

        String className = messageClass.getCanonicalName();
        if (person.getMessageQueue().containsKey(className)) {
            if (person.getMessageQueue().get(className).containsKey(fromPersonName)) {

                // send back a copy of the items instead of the original list
                List<U> messages = (List<U>) person.getMessageQueue().get(className).get(fromPersonName);

                if (createCopy) {
                    return Collections.unmodifiableList(messages);
                } else {
                    return messages;
                }
            }
        }

        // return an empty list
        return Collections.emptyList();

    } finally {
        lock.unlock();
    }
}