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:net.gbmb.collector.RecordController.java

@RequestMapping(value = "/records/{cid}/cancel", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
public Collection cancelCollection(@PathVariable("cid") String cid) throws CollectionStateException {
    Lock lock = hazelcast.getLock(cid);
    try {//from w w  w.j av  a 2 s .  co m
        lock.lock();
        Collection collection = collectionMap.get(cid);
        if (collection == null) {
            // collection not existing
            throw new ResourceNotFoundException(String.format("No collection with id '%s'", cid));
        }
        if (CollectionState.COLLECTING != collection.getState()) {
            // COLLECTING is the unique state that can be canceled
            throw new CollectionStateException(String.format("Cannot cancel collection '%s' in state '%s'",
                    collection.getId(), collection.getState().name()));
        }
        if (collection.isCancelable()) {
            // OK, can cancel
            collectionRecords.remove(cid);
            collectionMap.remove(cid);
            throw new NoContentException(String.format("Collection with id '%s' cancelled", cid));
        } else {
            // not cancelable so end the collection
            return markCollectionEnded(collection);
        }
    } finally {
        lock.unlock();
    }
}

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

@Override
public void removePolicy(CallContext callContext, String repositoryId, String policyId, String objectId,
        ExtensionsData extension) {//from w w w .j a  v  a 2s  .c o  m

    exceptionService.invalidArgumentRequiredString("objectId", objectId);
    exceptionService.invalidArgumentRequiredString("policyId", policyId);

    Lock objectLock = threadLockService.getWriteLock(repositoryId, objectId);
    Lock policyLock = threadLockService.getReadLock(repositoryId, policyId);
    try {
        objectLock.lock();
        policyLock.lock();

        // //////////////////
        // General Exception
        // //////////////////
        Content content = contentService.getContent(repositoryId, objectId);
        exceptionService.objectNotFound(DomainType.OBJECT, content, objectId);
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_REMOVE_POLICY_OBJECT,
                content);
        Policy policy = contentService.getPolicy(repositoryId, policyId);
        exceptionService.objectNotFound(DomainType.OBJECT, policy, policyId);
        exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_REMOVE_POLICY_POLICY,
                policy);

        // //////////////////
        // Body of the method
        // //////////////////
        contentService.removePolicy(callContext, repositoryId, policyId, objectId, extension);

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

    } finally {
        objectLock.unlock();
        policyLock.unlock();
    }
}

From source file:com.threecrickets.prudence.cache.SqlCache.java

public void invalidate(String tag) {
    try {/*from  w  w  w. j av a2  s  . c o  m*/
        Connection connection = connect();
        if (connection == null)
            return;

        try {
            List<String> tagged = getTagged(connection, tag);
            if (tagged.isEmpty())
                return;

            ArrayList<Lock> locks = new ArrayList<Lock>(tagged.size());

            String sql = "DELETE FROM " + cacheTableName + " WHERE key IN (";
            for (String key : tagged) {
                sql += "?,";
                locks.add(lockSource.getWriteLock(key));
            }
            sql = sql.substring(0, sql.length() - 1) + ")";

            for (Lock lock : locks)
                lock.lock();
            try {
                PreparedStatement statement = connection.prepareStatement(sql);
                try {
                    int i = 1;
                    for (String key : tagged)
                        statement.setString(i++, key);
                    if (!statement.execute())
                        logger.fine("Invalidated " + statement.getUpdateCount());
                } finally {
                    statement.close();
                }

                for (String key : tagged)
                    lockSource.discard(key);
            } finally {
                for (Lock lock : locks)
                    lock.unlock();
            }
        } finally {
            connection.close();
        }
    } catch (SQLException x) {
        logger.log(Level.WARNING, "Could not invalidate cache tag", x);
    }
}

From source file:de.taimos.daemon.spring.SpringDaemonAdapter.java

@Override
public final void doStart() throws Exception {
    super.doStart();
    try {//  ww w. j a v  a  2  s.co m
        this.doBeforeSpringStart();
    } catch (Exception e) {
        throw new RuntimeException("Before spring failed", e);
    }

    Lock writeLock = this.rwLock.writeLock();
    AbstractXmlApplicationContext ctx = null;
    try {
        writeLock.lock();
        if (this.context.get() != null) {
            throw new RuntimeException("Already started");
        }
        ctx = this.createSpringContext();
        String[] profiles = System.getProperty(Configuration.PROFILES, Configuration.PROFILES_PRODUCTION)
                .split(",");
        ctx.getEnvironment().setActiveProfiles(profiles);

        final PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        configurer.setProperties(DaemonStarter.getDaemonProperties());
        ctx.addBeanFactoryPostProcessor(configurer);

        ctx.setConfigLocation(this.getSpringResource());
        ctx.refresh();
    } catch (Exception e) {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e1) {
                this.logger.warn("Failed to close context", e1);
            }
            ctx = null;
        }
        throw new RuntimeException("Spring context failed", e);
    } finally {
        if (ctx != null) {
            this.context.set(ctx);
        }
        writeLock.unlock();
    }

    try {
        this.doAfterSpringStart();
    } catch (Exception e) {
        throw new RuntimeException("After spring failed", e);
    }
}

From source file:com.thoughtworks.studios.journey.JourneyService.java

/**
 * API for identify a user and setup traits.
 * @param ns: namespace under operation//from www .  j a  v a 2s .c  o  m
 * @param uid: unique identify for the user
 * @param anonymousId: anonymous_id to associate existing anonymous events
 * @param traitsJSON: request body for traits for the user
 * @return 201 response
 * @throws IOException
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/{ns}/identify")
public Response identify(@PathParam("ns") String ns, @QueryParam("uid") String uid,
        @QueryParam("anonymous_id") String anonymousId, String traitsJSON) throws IOException {
    Lock writingLock = getWritingLock(ns);
    writingLock.lock();

    try {
        Application app = new Application(graphDB, ns);
        Users users = app.users();

        try (Transaction tx = graphDB.beginTx()) {
            Node user = users.identify(uid, anonymousId);
            if (traitsJSON != null) {
                Map<String, Object> traits = jsonToMap(traitsJSON);
                for (String key : traits.keySet()) {
                    users.addTrait(user, key, traits.get(key));
                }
            }
            tx.success();
        }
    } finally {
        writingLock.unlock();
    }
    return Response.status(Response.Status.CREATED).build();
}

From source file:com.thoughtworks.studios.journey.JourneyService.java

/**
 * API for importing data exported via export api. The importing does not setup all the indexes,
 * so user need run /reindex api after importing.
 *
 * @param ns:     namespace/*from w w  w. jav a 2 s.  c om*/
 * @param stream: request body stream
 * @return 200 response if import success
 * @throws IOException
 */
@POST
@Produces(MediaType.TEXT_PLAIN)
@Path("/{ns}/import")
public Response imports(@PathParam("ns") String ns, InputStream stream) throws IOException {
    Lock writingLock = getWritingLock(ns);
    writingLock.lock();
    try {
        final Application app = new Application(graphDB, ns);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
        try (BatchTransaction tx = new BatchTransaction(graphDB, 1000)) {
            DataImportExport importer = new DataImportExport(app, new Reporter() {
                @Override
                public void report() {
                    tx.increment();
                }
            });
            importer.importFrom(bufferedReader);
        }
    } finally {
        writingLock.unlock();
    }
    return Response.status(Response.Status.OK).build();
}

From source file:org.pentaho.platform.plugin.action.olap.impl.OlapServiceImpl.java

/**
 * Returns a list of catalogs for the current session.
 *
 * <p>The cache is stored in the platform's caches in the region
 * {@link #CATALOG_CACHE_REGION}. It is also segmented by
 * locale, but we only return the correct sub-region according to the
 * session passed as a parameter./*from  w w  w  . j  a  v a  2s.  c  om*/
 */
@SuppressWarnings("unchecked")
protected synchronized List<IOlapService.Catalog> getCache(IPentahoSession session) {
    // Create the cache region if necessary.
    final ICacheManager cacheMgr = PentahoSystem.getCacheManager(session);
    final Object cacheKey = makeCacheSubRegionKey(getLocale());

    final Lock writeLock = cacheLock.writeLock();
    try {

        writeLock.lock();

        if (!cacheMgr.cacheEnabled(CATALOG_CACHE_REGION)) {
            // Create the region. This requires write access.
            cacheMgr.addCacheRegion(CATALOG_CACHE_REGION);
        }

        if (cacheMgr.getFromRegionCache(CATALOG_CACHE_REGION, cacheKey) == null) {
            // Create the sub-region. This requires write access.
            cacheMgr.putInRegionCache(CATALOG_CACHE_REGION, cacheKey, new ArrayList<IOlapService.Catalog>());
        }

        return (List<IOlapService.Catalog>) cacheMgr.getFromRegionCache(CATALOG_CACHE_REGION, cacheKey);

    } finally {
        writeLock.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();//  w  ww.  j  a va  2  s .  c  o  m
    try {
        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.nuxeo.nike.UpdateANikeDirectory.java

@OperationMethod
public void run() {
    Session directorySession = null;/*from  ww w.  jav a 2 s . c om*/
    CoreSession coreSession = null;

    Lock lock = new ReentrantLock();
    lock.lock();
    try {
        directorySession = directoryService.open(directoryName);

        // Delete all entries in the directory
        DocumentModelList entries = directorySession.getEntries();
        for (DocumentModel entry : entries) {
            directorySession.deleteEntry(entry);
        }

        // Query the documents and create unique entries
        coreSession = ctx.getCoreSession();
        String nxql = "SELECT * FROM " + docType;
        nxql += " WHERE ecm:currentLifeCycleState != 'deleted'";
        DocumentModelList allDocs = coreSession.query(nxql);

        List<String> titles = new ArrayList<String>();
        for (DocumentModel oneDoc : allDocs) {
            String title = oneDoc.getTitle();
            if (!titles.contains(title)) {
                titles.add(title);

                Map<String, Object> entry = new HashMap<String, Object>();
                entry.put("id", title);
                entry.put("label", title);
                entry.put("obsolete", 0);
                entry.put("ordering", 10000);

                directorySession.createEntry(entry);
            }
        }
        directorySession.close();

    } catch (Exception e) {
        log.error("Error creating the directory", e);
    } finally {
        lock.unlock();
    }
}

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

/**
 * One-argument version of {@link #mostSimilarItems(String[], int, PairRescorer)}.
 *//*from   w  w w  . j a  v a 2  s.co  m*/
@Override
public List<IDValue> mostSimilarItems(String itemID, int howMany, PairRescorer rescorer)
        throws NoSuchItemException, NotReadyException {

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

    long longItemID = StringLongMapping.toLong(itemID);

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

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

        float[] itemFeatures = Y.get(longItemID);
        if (itemFeatures == null) {
            throw new NoSuchItemException(itemID);
        }

        return translateToStringIDs(
                TopN.selectTopN(new MostSimilarItemIterator(Y.entrySet().iterator(), new long[] { longItemID },
                        new float[][] { itemFeatures }, rescorer, generation.getIDMapping()), howMany));
    } finally {
        yLock.unlock();
    }

}