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:org.apache.rave.opensocial.service.impl.DefaultAppDataService.java

/**
 * Updates app data for the specified user and group with the new values.
 *
 * @param userId  The user/*from w ww  . j  a v  a 2 s . com*/
 * @param groupId The group
 * @param appId   The application ID
 * @param fields  The fields to update.  Empty set implies that all fields that should be persisted have been
 *                provided in the values map (completely replace current appData with new data).  A key in the
 *                fields set without a corresponding key in the values map implies a delete of that field.
 *                A key in the values map not present in the fields set is a bad request.
 * @param values  The values to set
 * @param token   The security token
 * @return an error if one occurs
 */
@Override
public Future<Void> updatePersonData(UserId userId, GroupId groupId, String appId, Set<String> fields,
        Map<String, Object> values, SecurityToken token) throws ProtocolException {
    //make sure the request conforms to the OpenSocial visibility rules
    String personId = validateWriteRequest(userId, groupId, appId, token);

    //lock on this user and this application to avoid any potential concurrency issues
    Lock lock = getApplicationDataLock(personId, appId);
    try {
        lock.lock();
        //get the application data for this user and application
        ApplicationData applicationData = applicationDataRepository.getApplicationData(personId, appId);

        //if there is no data, create an empty object to store the data in that we'll save when we're done
        if (applicationData == null) {
            applicationData = new ApplicationDataImpl(null, personId, appId, new HashMap<String, Object>());
        }

        //if the fields parameter is empty, we can just use the values map directly since this is a full update
        if (fields == null || fields.size() == 0) {
            applicationData.setData(values);
        }
        //if there are keys in the values map that aren't in the fields set, its a bad request
        else if (!fields.containsAll(values.keySet())) {
            throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST,
                    "Fields parameter must either be empty or contain keys "
                            + "for all name value pairs sent in request.");
        }
        //we have a partial update - we know that the fields set contains keys for all the entries in the values
        //map (due to the check above), so we can just enumerate over it now to finish our work.  So we want to remove
        //any fields found in the fields set that are not found in the values map and update the rest.
        else {
            Map<String, Object> data = applicationData.getData();
            for (String field : fields) {
                //if this field is not in the values map, its a delete
                if (!values.containsKey(field)) {
                    data.remove(field);
                } else {
                    //its an update
                    data.put(field, values.get(field));
                }
            }
        }

        //save our changes and return
        applicationDataRepository.save(applicationData);
    } finally {
        lock.unlock();
        lockService.returnLock(lock);
    }
    return Futures.immediateFuture(null);
}

From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java

@Override
public void massUpdatePredecessors(Integer taskSourceId, final List<TaskPredecessor> predecessors,
        Integer sAccountId) {/*from   www . j av a 2 s .c  o m*/
    Lock lock = DistributionLockUtil.getLock("task-service" + sAccountId);
    try {
        PredecessorMapper predecessorMapper = ApplicationContextUtil.getSpringBean(PredecessorMapper.class);
        PredecessorExample ex = new PredecessorExample();
        ex.createCriteria().andSourceidEqualTo(taskSourceId);
        predecessorMapper.deleteByExample(ex);

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        final long now = new GregorianCalendar().getTimeInMillis();
        if (lock.tryLock(30, TimeUnit.SECONDS)) {
            jdbcTemplate.batchUpdate(
                    "INSERT INTO `m_prj_predecessor`(`sourceType`, `descType`, `predestype`,`lagDay`, "
                            + "`sourceId`,`descId`, `createdTime`) VALUES (?, ?, ?, ?, ?, ?, ?)",
                    new BatchPreparedStatementSetter() {
                        @Override
                        public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                            preparedStatement.setString(1, predecessors.get(i).getSourcetype());
                            preparedStatement.setString(2, predecessors.get(i).getDesctype());
                            preparedStatement.setString(3, predecessors.get(i).getPredestype());
                            preparedStatement.setInt(4, predecessors.get(i).getLagday());
                            preparedStatement.setInt(5, predecessors.get(i).getSourceid());
                            preparedStatement.setInt(6, predecessors.get(i).getDescid());
                            preparedStatement.setDate(7, new Date(now));
                        }

                        @Override
                        public int getBatchSize() {
                            return predecessors.size();
                        }
                    });
        }
    } catch (Exception e) {
        throw new MyCollabException(e);
    } finally {
        DistributionLockUtil.removeLock("task-service" + sAccountId);
        lock.unlock();
    }
}

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

@Override
public float[] similarityToItem(long toItemID, long... itemIDs) throws TasteException {

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

    float[] similarities = new float[itemIDs.length];
    Lock yLock = generation.getYLock().readLock();
    yLock.lock();/*ww w.  j av a  2  s .  com*/
    try {

        float[] toFeatures = Y.get(toItemID);
        if (toFeatures == null) {
            throw new NoSuchItemException(toItemID);
        }
        double toFeaturesNorm = SimpleVectorMath.norm(toFeatures);

        boolean anyFound = false;
        for (int i = 0; i < similarities.length; i++) {
            float[] features = Y.get(itemIDs[i]);
            if (features == null) {
                similarities[i] = Float.NaN;
            } else {
                anyFound = true;
                double featuresNorm = SimpleVectorMath.norm(features);
                similarities[i] = (float) (SimpleVectorMath.dot(features, toFeatures)
                        / (featuresNorm * toFeaturesNorm));
            }
        }
        if (!anyFound) {
            throw new NoSuchItemException(Arrays.toString(itemIDs));
        }

    } finally {
        yLock.unlock();
    }

    return similarities;
}

From source file:org.onosproject.drivers.bmv2.Bmv2FlowRuleProgrammable.java

private Collection<FlowRule> processFlowRules(Collection<FlowRule> rules, Operation operation) {

    if (!init()) {
        return Collections.emptyList();
    }/*from w  ww  . ja  v  a 2  s.  c o  m*/

    DeviceId deviceId = handler().data().deviceId();

    Bmv2DeviceAgent deviceAgent;
    try {
        deviceAgent = controller.getAgent(deviceId);
    } catch (Bmv2RuntimeException e) {
        log.error("Failed to get BMv2 device agent: {}", e.explain());
        return Collections.emptyList();
    }

    Bmv2DeviceContext context = contextService.getContext(deviceId);
    if (context == null) {
        log.error("Unable to get device context for {}", deviceId);
        return Collections.emptyList();
    }

    Bmv2FlowRuleTranslator translator = tableEntryService.getFlowRuleTranslator();

    List<FlowRule> processedFlowRules = Lists.newArrayList();

    for (FlowRule rule : rules) {

        Bmv2TableEntry bmv2Entry;

        try {
            bmv2Entry = translator.translate(rule, context);
        } catch (Bmv2FlowRuleTranslatorException e) {
            log.warn("Unable to translate flow rule: {} - {}", e.getMessage(), rule);
            continue; // next rule
        }

        String tableName = bmv2Entry.tableName();
        Bmv2TableEntryReference entryRef = new Bmv2TableEntryReference(deviceId, tableName,
                bmv2Entry.matchKey());

        Lock lock = ENTRY_LOCKS.computeIfAbsent(entryRef, k -> new ReentrantLock());
        lock.lock();
        try {
            // Get from store
            Bmv2FlowRuleWrapper frWrapper = tableEntryService.lookup(entryRef);
            try {
                if (operation == Operation.APPLY) {
                    // Apply entry
                    long entryId;
                    if (frWrapper != null) {
                        // Existing entry.
                        entryId = frWrapper.entryId();
                        // Tentatively delete entry before re-adding.
                        // It might not exist on device due to inconsistencies.
                        silentlyRemove(deviceAgent, entryRef.tableName(), entryId);
                    }
                    // Add entry.
                    entryId = doAddEntry(deviceAgent, bmv2Entry);
                    frWrapper = new Bmv2FlowRuleWrapper(rule, entryId, System.currentTimeMillis());
                } else {
                    // Remove entry
                    if (frWrapper == null) {
                        // Entry not found in map, how come?
                        forceRemove(deviceAgent, entryRef.tableName(), entryRef.matchKey());
                    } else {
                        long entryId = frWrapper.entryId();
                        doRemove(deviceAgent, entryRef.tableName(), entryId, entryRef.matchKey());
                    }
                    frWrapper = null;
                }
                // If here, no exceptions... things went well :)
                processedFlowRules.add(rule);
            } catch (Bmv2RuntimeException e) {
                log.warn("Unable to {} flow rule: {}", operation.name(), e.explain());
            }

            // Update entryRef binding in table entry service.
            if (frWrapper != null) {
                tableEntryService.bind(entryRef, frWrapper);
            } else {
                tableEntryService.unbind(entryRef);
            }
        } finally {
            lock.unlock();
        }
    }

    return processedFlowRules;
}

From source file:org.marketcetera.marketdata.core.provider.AbstractMarketDataProvider.java

@Override
public void cancelMarketDataRequest(MarketDataRequestToken inRequestToken) {
    // TODO re-exploding the request might cause problems if the request itself changed, better to associate the token ID
    //  with a set of atoms
    Lock cancelLock = marketdataLock.writeLock();
    try {/*  w  ww .j a va  2  s .  c  om*/
        cancelLock.lockInterruptibly();
        Set<MarketDataRequestAtom> atoms = explodeRequest(inRequestToken.getRequest());
        for (MarketDataRequestAtom atom : atoms) {
            Collection<MarketDataRequestToken> symbolRequests = requestsByAtom.get(atom);
            if (symbolRequests != null) {
                symbolRequests.remove(inRequestToken);
                if (symbolRequests.isEmpty()) {
                    doCancel(atom);
                }
            }
            Collection<MarketDataRequestToken> requests = requestsBySymbol.get(atom.getSymbol());
            if (requests != null) {
                requests.remove(inRequestToken);
            }
            Instrument mappedInstrument = instrumentsBySymbol.get(atom.getSymbol());
            if (mappedInstrument != null) {
                Collection<MarketDataRequestToken> instrumentRequests = requestsByInstrument
                        .get(mappedInstrument);
                if (instrumentRequests != null) {
                    instrumentRequests.remove(inRequestToken);
                    if (instrumentRequests.isEmpty()) {
                        // no more requests for this instrument, which means this instrument will no longer be updated - clear the cache for it
                        cachedMarketdata.remove(mappedInstrument);
                    }
                }
            }
        }
    } catch (InterruptedException e) {
        org.marketcetera.marketdata.core.Messages.UNABLE_TO_ACQUIRE_LOCK.error(this);
        stop();
    } finally {
        cancelLock.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) {/*  ww w .j  a  va2 s. c  om*/

    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:org.opendedup.collections.ProgressiveFileBasedCSMap.java

@Override
public InsertRecord put(ChunkData cm, boolean persist) throws IOException, HashtableFullException {
    // persist = false;
    if (this.isClosed())
        throw new HashtableFullException("Hashtable " + this.fileName + " is close");
    if (kSz.get() >= this.maxSz)
        throw new HashtableFullException("maximum sized reached");
    InsertRecord rec = null;/*from  ww w  .  j  av  a 2  s.  co m*/
    // if (persist)
    // this.flushFullBuffer();
    Lock l = gcLock.readLock();
    l.lock();
    ProgressiveFileByteArrayLongMap bm = null;
    try {
        // long tm = System.currentTimeMillis();
        AbstractShard rm = this.getReadMap(cm.getHash());
        if (rm == null) {
            // this.misses.incrementAndGet();
            // tm = System.currentTimeMillis() - tm;
            while (rec == null) {
                try {
                    if (persist && !cm.recoverd) {
                        try {
                            cm.persistData(true);
                        } catch (HashExistsException e) {
                            return new InsertRecord(false, e.getPos());
                        }
                    }
                    bm = this.getWriteMap();
                    rec = bm.put(cm.getHash(), cm.getcPos());
                    this.lbf.put(cm.getHash());
                } catch (HashtableFullException e) {
                    rec = null;
                } catch (Exception e) {
                    throw e;
                }
            }
        } else {
            try {
                rec = new InsertRecord(false, rm.get(cm.getHash()));
            } catch (MapClosedException e) {
                SDFSLogger.getLog().error("unable to remove", e);
            }
        }
        // this.msTr.addAndGet(tm);

    } finally {
        try {
            if (bm != null) {
                bm.activate();
            }
        } catch (Exception e) {

        } finally {
            l.unlock();
        }
    }
    /*
     * this.trs.incrementAndGet(); if(this.trs.get() == 10000) { long tpm =
     * 0; if(this.misses.get() > 0) tpm = this.msTr.get()/this.misses.get();
     * SDFSLogger.getLog().info("trs=" + this.trs.get() + " misses=" +
     * this.misses.get() + " mtm=" + this.msTr.get() + " tpm=" + tpm);
     * this.trs.set(0); this.misses.set(0); this.msTr.set(0); }
     */
    if (rec.getInserted())
        this.kSz.incrementAndGet();
    return rec;
}

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.  ja v  a2  s . c  om
        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:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java

private void massUpdateBugGanttItems(final List<TaskGanttItem> taskGanttItems, Integer sAccountId) {
    if (CollectionUtils.isNotEmpty(taskGanttItems)) {
        Lock lock = DistributionLockUtil.getLock("gantt-bug-service" + sAccountId);
        try {//from ww w  . j a v a  2s. c  o  m
            final long now = new GregorianCalendar().getTimeInMillis();
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                try (Connection connection = dataSource.getConnection()) {
                    connection.setAutoCommit(false);
                    PreparedStatement batchTasksStatement = connection.prepareStatement(
                            "UPDATE `m_tracker_bug` SET " + "summary = ?, `startdate` = ?, `enddate` = ?, "
                                    + "`lastUpdatedTime`=?, `percentagecomplete`=?, `assignuser`=?, `ganttindex`=?, "
                                    + "`milestoneId`=? WHERE `id` = ?");
                    for (int i = 0; i < taskGanttItems.size(); i++) {
                        TaskGanttItem ganttItem = taskGanttItems.get(i);
                        if (ProjectTypeConstants.BUG.equals(ganttItem.getType())) {
                            batchTasksStatement.setString(1, ganttItem.getName());
                            batchTasksStatement.setDate(2, getDateWithNullValue(ganttItem.getStartDate()));
                            batchTasksStatement.setDate(3, getDateWithNullValue(ganttItem.getEndDate()));
                            batchTasksStatement.setDate(4, new Date(now));
                            batchTasksStatement.setDouble(5,
                                    MoreObjects.firstNonNull(ganttItem.getProgress(), 0d));
                            batchTasksStatement.setString(6, ganttItem.getAssignUser());
                            batchTasksStatement.setInt(7, ganttItem.getGanttIndex());
                            batchTasksStatement.setObject(8, ganttItem.getMilestoneId());
                            batchTasksStatement.setInt(9, ganttItem.getId());
                            batchTasksStatement.addBatch();
                        }

                    }
                    batchTasksStatement.executeBatch();
                    connection.commit();
                }
            }
        } catch (Exception e) {
            throw new MyCollabException(e);
        } finally {
            DistributionLockUtil.removeLock("gantt-bug-service" + sAccountId);
            lock.unlock();
        }
    }
}

From source file:org.springframework.integration.aggregator.AbstractCorrelatingMessageHandler.java

private void forceComplete(MessageGroup group) {

    Object correlationKey = group.getGroupId();
    // UUIDConverter is no-op if already converted
    Lock lock = this.lockRegistry.obtain(UUIDConverter.getUUID(correlationKey).toString());
    boolean removeGroup = true;
    try {//from   www.  ja va 2s . c o m
        lock.lockInterruptibly();
        try {
            /*
             * Refetch the group because it might have changed while we were waiting on
             * its lock. If the last modified timestamp changed, defer the completion
             * because the selection condition may have changed such that the group
             * would no longer be eligible.
             */
            MessageGroup groupNow = this.messageStore.getMessageGroup(group.getGroupId());
            long lastModifiedNow = groupNow.getLastModified();
            if (group.getLastModified() == lastModifiedNow) {
                if (groupNow.size() > 0) {
                    if (releaseStrategy.canRelease(groupNow)) {
                        this.completeGroup(correlationKey, groupNow);
                    } else {
                        this.expireGroup(correlationKey, groupNow);
                    }
                } else {
                    /*
                     * By default empty groups are removed on the same schedule as non-empty
                     * groups. A longer timeout for empty groups can be enabled by
                     * setting minimumTimeoutForEmptyGroups.
                     */
                    removeGroup = lastModifiedNow <= (System.currentTimeMillis()
                            - this.minimumTimeoutForEmptyGroups);
                    if (removeGroup && logger.isDebugEnabled()) {
                        logger.debug("Removing empty group: " + correlationKey);
                    }
                }
            } else {
                removeGroup = false;
                if (logger.isDebugEnabled()) {
                    logger.debug("Group expiry candidate (" + correlationKey
                            + ") has changed - it may be reconsidered for a future expiration");
                }
            }
        } finally {
            if (removeGroup) {
                this.remove(group);
            }
            lock.unlock();
        }
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        throw new MessagingException("Thread was interrupted while trying to obtain lock");
    }
}