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

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

Introduction

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

Prototype

lock

Source Link

Usage

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

@Override
public void updateProperties(CallContext callContext, String repositoryId, Holder<String> objectId,
        Properties properties, Holder<String> changeToken) {

    exceptionService.invalidArgumentRequiredHolderString("objectId", objectId);

    Lock lock = threadLockService.getWriteLock(repositoryId, objectId.getValue());
    try {//www .  j  a  va2 s. c o m
        lock.lock();

        // //////////////////
        // Exception
        // //////////////////
        Content content = checkExceptionBeforeUpdateProperties(callContext, repositoryId, objectId, properties,
                changeToken);

        // //////////////////
        // Body of the method
        // //////////////////
        contentService.updateProperties(callContext, repositoryId, properties, content);

        nemakiCachePool.get(repositoryId).removeCmisCache(objectId.getValue());
    } finally {
        lock.unlock();
    }
}

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

@Override
public void deleteContentStream(CallContext callContext, String repositoryId, Holder<String> objectId,
        Holder<String> changeToken, ExtensionsData extension) {

    exceptionService.invalidArgumentRequiredHolderString("objectId", objectId);

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

        // //////////////////
        // Exception
        // //////////////////
        Document document = contentService.getDocument(repositoryId, objectId.getValue());
        exceptionService.objectNotFound(DomainType.OBJECT, document, document.getId());
        exceptionService.constraintContentStreamRequired(repositoryId, document);

        // //////////////////
        // Body of the method
        // //////////////////
        contentService.deleteContentStream(callContext, repositoryId, objectId);

        nemakiCachePool.get(repositoryId).removeCmisCache(objectId.getValue());

    } finally {
        lock.unlock();
    }
}

From source file:com.cloudera.oryx.als.serving.ServerRecommender.java

@Override
public void removePreference(String userID, String itemID) {

    // Record datum
    try {/*from  www  .  j  a v  a 2 s. c o  m*/
        generationManager.remove(userID, itemID);
    } catch (IOException ioe) {
        log.warn("Could not append datum; continuing", ioe);
    }

    Generation generation;
    try {
        generation = getCurrentGeneration();
    } catch (NotReadyException nre) {
        // Corner case -- no model ready so all we can do is record (above). Don't fail the request.
        return;
    }

    long longUserID = StringLongMapping.toLong(userID);
    long longItemID = StringLongMapping.toLong(itemID);

    ReadWriteLock knownItemLock = generation.getKnownItemLock();

    boolean removeUser = false;
    LongObjectMap<LongSet> knownItemIDs = generation.getKnownItemIDs();
    if (knownItemIDs != null) {

        Lock knownItemReadLock = knownItemLock.readLock();
        LongSet userKnownItemIDs;
        knownItemReadLock.lock();
        try {
            userKnownItemIDs = knownItemIDs.get(longUserID);
        } finally {
            knownItemReadLock.unlock();
        }

        if (userKnownItemIDs == null) {
            // Doesn't exist? So ignore this request
            return;
        }

        synchronized (userKnownItemIDs) {
            if (!userKnownItemIDs.remove(longItemID)) {
                // Item unknown, so ignore this request
                return;
            }
            removeUser = userKnownItemIDs.isEmpty();
        }
    }

    // We can proceed with the request

    LongObjectMap<float[]> X = generation.getX();

    ReadWriteLock xLock = generation.getXLock();

    if (removeUser) {

        Lock knownItemWriteLock = knownItemLock.writeLock();
        knownItemWriteLock.lock();
        try {
            knownItemIDs.remove(longUserID);
        } finally {
            knownItemWriteLock.unlock();
        }

        Lock xWriteLock = xLock.writeLock();
        xWriteLock.lock();
        try {
            X.remove(longUserID);
        } finally {
            xWriteLock.unlock();
        }

    }

}

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

@Override
public void moveObject(CallContext callContext, String repositoryId, Holder<String> objectId,
        String sourceFolderId, String targetFolderId) {

    exceptionService.invalidArgumentRequiredHolderString("objectId", objectId);

    Lock lock = threadLockService.getWriteLock(repositoryId, objectId.getValue());
    try {// w  w w  .j  a  va  2s  .c o m
        lock.lock();
        // //////////////////
        // General Exception
        // //////////////////
        exceptionService.invalidArgumentRequiredString("sourceFolderId", sourceFolderId);
        exceptionService.invalidArgumentRequiredString("targetFolderId", targetFolderId);
        Content content = contentService.getContent(repositoryId, objectId.getValue());
        exceptionService.objectNotFound(DomainType.OBJECT, content, objectId.getValue());
        Folder source = contentService.getFolder(repositoryId, sourceFolderId);
        exceptionService.objectNotFound(DomainType.OBJECT, source, sourceFolderId);
        Folder target = contentService.getFolder(repositoryId, targetFolderId);
        exceptionService.objectNotFound(DomainType.OBJECT, target, targetFolderId);
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_MOVE_OBJECT,
                content);
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_MOVE_SOURCE, source);
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_MOVE_TARGET, target);

        // //////////////////
        // Body of the method
        // //////////////////
        contentService.move(callContext, repositoryId, content, target);

        nemakiCachePool.get(repositoryId).removeCmisCache(content.getId());
    } finally {
        lock.unlock();
    }
}

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

@Override
public void appendContentStream(CallContext callContext, String repositoryId, Holder<String> objectId,
        Holder<String> changeToken, ContentStream contentStream, boolean isLastChunk,
        ExtensionsData extension) {//from ww w  . java 2  s  .  c  o m

    exceptionService.invalidArgumentRequiredHolderString("objectId", objectId);

    Lock lock = threadLockService.getWriteLock(repositoryId, objectId.getValue());
    try {
        lock.lock();

        // //////////////////
        // General Exception
        // //////////////////

        exceptionService.invalidArgumentRequired("contentStream", contentStream);
        Document doc = (Document) contentService.getContent(repositoryId, objectId.getValue());
        exceptionService.objectNotFound(DomainType.OBJECT, doc, objectId.getValue());
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_SET_CONTENT_DOCUMENT,
                doc);
        DocumentTypeDefinition td = (DocumentTypeDefinition) typeManager.getTypeDefinition(repositoryId,
                doc.getObjectType());
        exceptionService.constraintImmutable(repositoryId, doc, td);

        // //////////////////
        // Specific Exception
        // //////////////////
        exceptionService.streamNotSupported(td, contentStream);
        exceptionService.updateConflict(doc, changeToken);
        exceptionService.versioning(doc);

        // //////////////////
        // Body of the method
        // //////////////////
        contentService.appendAttachment(callContext, repositoryId, objectId, changeToken, contentStream,
                isLastChunk, extension);

        nemakiCachePool.get(repositoryId).removeCmisCache(objectId.getValue());
    } finally {
        lock.unlock();
    }
}

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

@Override
public void setContentStream(CallContext callContext, String repositoryId, Holder<String> objectId,
        boolean overwriteFlag, ContentStream contentStream, Holder<String> changeToken) {

    exceptionService.invalidArgumentRequiredHolderString("objectId", objectId);

    Lock lock = threadLockService.getWriteLock(repositoryId, objectId.getValue());
    try {//from ww w  .j  av  a  2  s.  c  o m
        lock.lock();
        // //////////////////
        // General Exception
        // //////////////////

        exceptionService.invalidArgumentRequired("contentStream", contentStream);
        Document doc = (Document) contentService.getContent(repositoryId, objectId.getValue());
        exceptionService.objectNotFound(DomainType.OBJECT, doc, objectId.getValue());
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_SET_CONTENT_DOCUMENT,
                doc);
        DocumentTypeDefinition td = (DocumentTypeDefinition) typeManager.getTypeDefinition(repositoryId,
                doc.getObjectType());
        exceptionService.constraintImmutable(repositoryId, doc, td);

        // //////////////////
        // Specific Exception
        // //////////////////
        exceptionService.contentAlreadyExists(doc, overwriteFlag);
        exceptionService.streamNotSupported(td, contentStream);
        exceptionService.updateConflict(doc, changeToken);
        exceptionService.versioning(doc);
        Folder parent = contentService.getParent(repositoryId, objectId.getValue());
        exceptionService.objectNotFoundParentFolder(repositoryId, objectId.getValue(), parent);

        // //////////////////
        // Body of the method
        // //////////////////
        String oldId = objectId.getValue();

        // TODO Externalize versioningState
        if (doc.isPrivateWorkingCopy()) {
            Document result = contentService.replacePwc(callContext, repositoryId, doc, contentStream);
            objectId.setValue(result.getId());
        } else {
            Document result = contentService.createDocumentWithNewStream(callContext, repositoryId, doc,
                    contentStream);
            objectId.setValue(result.getId());
        }

        nemakiCachePool.get(repositoryId).removeCmisCache(oldId);
    } finally {
        lock.unlock();
    }
}

From source file:com.cloudera.oryx.als.serving.ServerRecommender.java

@Override
public List<IDValue> recommendToMany(String[] userIDs, int howMany, boolean considerKnownItems,
        Rescorer rescorer) throws NoSuchUserException, NotReadyException {

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

    Generation generation = getCurrentGeneration();
    LongObjectMap<float[]> X = generation.getX();

    Lock xLock = generation.getXLock().readLock();
    List<float[]> userFeatures = Lists.newArrayListWithCapacity(userIDs.length);
    xLock.lock();
    try {//from   ww  w.  ja  va  2 s .  co m
        for (String userID : userIDs) {
            float[] theUserFeatures = X.get(StringLongMapping.toLong(userID));
            if (theUserFeatures != null) {
                userFeatures.add(theUserFeatures);
            }
        }
    } finally {
        xLock.unlock();
    }
    if (userFeatures.isEmpty()) {
        throw new NoSuchUserException(Arrays.toString(userIDs));
    }

    LongObjectMap<LongSet> knownItemIDs = generation.getKnownItemIDs();
    if (knownItemIDs == null && !considerKnownItems) {
        throw new UnsupportedOperationException("Can't ignore known items because no known items available");
    }
    LongSet usersKnownItemIDs = null;
    if (!considerKnownItems) {
        Lock knownItemLock = generation.getKnownItemLock().readLock();
        knownItemLock.lock();
        try {
            for (String userID : userIDs) {
                LongSet theKnownItemIDs = knownItemIDs.get(StringLongMapping.toLong(userID));
                if (theKnownItemIDs == null) {
                    continue;
                }
                if (usersKnownItemIDs == null) {
                    usersKnownItemIDs = theKnownItemIDs;
                } else {
                    LongPrimitiveIterator it = usersKnownItemIDs.iterator();
                    while (it.hasNext()) {
                        if (!theKnownItemIDs.contains(it.nextLong())) {
                            it.remove();
                        }
                    }
                }
                if (usersKnownItemIDs.isEmpty()) {
                    break;
                }
            }
        } finally {
            knownItemLock.unlock();
        }
    }

    float[][] userFeaturesArray = userFeatures.toArray(new float[userFeatures.size()][]);
    Lock yLock = generation.getYLock().readLock();
    yLock.lock();
    try {
        return multithreadedTopN(userFeaturesArray, usersKnownItemIDs, rescorer, howMany,
                generation.getCandidateFilter());
    } finally {
        yLock.unlock();
    }

}

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

@Override
public boolean mightContainKey(byte[] key) {
    Lock l = gcLock.readLock();
    l.lock();
    try {//from w  w  w.  java  2  s  .c  o  m
        if (!this.runningGC)
            return this.lbf.mightContain(key);
        else {
            long ps = -1;
            try {
                ps = this.get(key);
            } catch (IOException e) {
                SDFSLogger.getLog().warn("unable to check", e);
                return true;
            }
            if (ps != -1) {
                return true;
            } else
                return false;
        }

    } finally {
        l.unlock();
    }
}

From source file:org.apache.nifi.cluster.coordination.http.replication.ThreadPoolRequestReplicator.java

@Override
public AsyncClusterResponse replicate(Set<NodeIdentifier> nodeIds, String method, URI uri, Object entity,
        Map<String, String> headers, final boolean indicateReplicated, final boolean performVerification) {
    final Map<String, String> updatedHeaders = new HashMap<>(headers);

    updatedHeaders.put(RequestReplicator.CLUSTER_ID_GENERATION_SEED_HEADER,
            ComponentIdGenerator.generateId().toString());
    if (indicateReplicated) {
        updatedHeaders.put(RequestReplicator.REPLICATION_INDICATOR_HEADER, "true");
    }//from w  w w  . ja v a  2  s. co  m

    // include the proxied entities header
    updateRequestHeaders(updatedHeaders);

    if (indicateReplicated) {
        // If we are replicating a request and indicating that it is replicated, then this means that we are
        // performing an action, rather than simply proxying the request to the cluster coordinator. In this case,
        // we need to ensure that we use proper locking. We don't want two requests modifying the flow at the same
        // time, so we use a write lock if the request is mutable and a read lock otherwise.
        final Lock lock = isMutableRequest(method, uri.getPath()) ? writeLock : readLock;
        logger.debug("Obtaining lock {} in order to replicate request {} {}", lock, method, uri);
        lock.lock();
        try {
            logger.debug("Lock {} obtained in order to replicate request {} {}", lock, method, uri);

            // Unlocking of the lock is performed within the replicate method, as we need to ensure that it is unlocked only after
            // the entire request has completed.
            final Object monitor = new Object();
            synchronized (monitor) {
                final AsyncClusterResponse response = replicate(nodeIds, method, uri, entity, updatedHeaders,
                        performVerification, null, !performVerification, true, monitor);

                try {
                    monitor.wait();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }

                return response;
            }
        } finally {
            lock.unlock();
            logger.debug("Unlocked {} after replication completed for {} {}", lock, method, uri);
        }
    } else {
        return replicate(nodeIds, method, uri, entity, updatedHeaders, performVerification, null,
                !performVerification, true, null);
    }
}

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

@Override
public boolean claimKey(byte[] hash, long val, long ct) throws IOException {
    Lock l = gcLock.readLock();
    l.lock();
    try {//from   w  w  w  .  j a v a 2s. c  o  m
        if (!runningGC && !lbf.mightContain(hash)) {
            return false;
        }
        AbstractShard k = this.keyLookup.getIfPresent(new ByteArrayWrapper(hash));
        if (k != null) {
            try {
                boolean pos = k.claim(hash, val, ct);
                if (pos) {
                    // m.cache();
                    return pos;
                }
            } catch (MapClosedException e) {
                this.keyLookup.invalidate(new ByteArrayWrapper(hash));
            }
        }
        for (AbstractShard m : this.maps.getAL()) {
            try {
                boolean pos = m.claim(hash, val, ct);
                if (pos) {
                    // m.cache();
                    return pos;
                }
            } catch (MapClosedException e) {
            }
        }
        SDFSLogger.getLog().info("miss2");
        return false;
    } finally {
        l.unlock();
    }
}