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.cloudera.oryx.als.serving.ServerRecommender.java

@Override
public List<IDValue> recommendToAnonymous(String[] itemIDs, float[] values, int howMany, Rescorer rescorer)
        throws NotReadyException, NoSuchItemException {

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

    float[] anonymousUserFeatures = buildAnonymousUserFeatures(itemIDs, values);

    LongSet userKnownItemIDs = new LongSet(itemIDs.length);
    for (String itemID : itemIDs) {
        userKnownItemIDs.add(StringLongMapping.toLong(itemID));
    }//ww  w .  j a  va 2 s  .  c  o  m

    float[][] anonymousFeaturesAsArray = { anonymousUserFeatures };

    Generation generation = getCurrentGeneration();
    Lock yLock = generation.getYLock().readLock();
    yLock.lock();
    try {
        return multithreadedTopN(anonymousFeaturesAsArray, userKnownItemIDs, rescorer, howMany,
                generation.getCandidateFilter());
    } finally {
        yLock.unlock();
    }
}

From source file:org.apache.rave.opensocial.service.impl.DefaultAppDataService.java

/**
 * Deletes data for the specified user and group.
 *
 * @param userId  The user/*from w  ww  .  j a  v a 2  s.  co m*/
 * @param groupId The group
 * @param appId   The application ID
 * @param fields  The fields to delete - empty set implies all fields
 * @param token   The security token
 * @return an error if one occurs
 */
@Override
public Future<Void> deletePersonData(UserId userId, GroupId groupId, String appId, Set<String> fields,
        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, there's nothing to delete, so we're done...
        if (applicationData == null || applicationData.getData() == null) {
            return Futures.immediateFuture(null);
        }

        //remove the fields specified -- empty field set implies remove all, otherwise remove just the fields specified
        Map<String, Object> data = applicationData.getData();
        if (fields == null || fields.size() == 0) {
            data.clear();
        } else {
            data.keySet().removeAll(fields);
        }

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

From source file:be.fgov.kszbcss.rhq.websphere.config.CellConfiguration.java

private void discardSession(boolean destroy) {
    Lock writeLock = sessionLock.writeLock();
    writeLock.lock();//from  w w w .j av a2 s. com
    try {
        if (session != null) {
            if (log.isDebugEnabled()) {
                log.debug("Discarding session " + session);
            }
            try {
                configService.discard(session);
            } catch (Exception ex) {
                log.warn("Unexpected exception when discarding workspace " + session, ex);
            }
            synchronized (resolverCache) {
                log.debug("Clearing resolver cache");
                resolverCache.clear();
            }
            synchronized (configObjectCache) {
                log.debug("Clearing config object cache");
                configObjectCache.clear();
            }
        }
        if (destroy) {
            destroyed = true;
        }
    } finally {
        writeLock.unlock();
    }
}

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

/**
 * Delete an entry./*from   www  .j  a va 2s .c o  m*/
 * 
 * @param connection
 *        The connection
 * @param key
 *        The key
 * @throws SQLException
 */
private void delete(Connection connection, String key) throws SQLException {
    Lock lock = lockSource.getWriteLock(key);
    lock.lock();
    try {
        String sql = "DELETE FROM " + cacheTableName + " WHERE key=?";
        PreparedStatement statement = connection.prepareStatement(sql);
        try {
            statement.setString(1, key);
            if (!statement.execute()) {
                if (logger.isLoggable(Level.FINE) && statement.getUpdateCount() > 0)
                    logger.fine("Deleted: " + key);
            }
        } finally {
            statement.close();
        }
    } finally {
        lock.unlock();
        lockSource.discard(key);
    }
}

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

/**
 * <p>Lists the items that were most influential in recommending a given item to a given user. Exactly how this
 * is determined is left to the implementation, but, generally this will return items that the user prefers
 * and that are similar to the given item.</p>
 *
 * <p>These values by which the results are ordered are opaque values and have no interpretation
 * other than that larger means stronger.</p>
 *
 * @param userID ID of user who was recommended the item
 * @param itemID ID of item that was recommended
 * @param howMany maximum number of items to return
 * @return {@link List} of {@link IDValue}, ordered from most influential in recommended the given
 *  item to least//from w  ww.j a v  a2  s . c om
 * @throws NoSuchUserException if the user is not known in the model
 * @throws NoSuchItemException if the item is not known in the model
 * @throws NotReadyException if the recommender has no model available yet
 */
@Override
public List<IDValue> recommendedBecause(String userID, String itemID, int howMany)
        throws NoSuchUserException, NoSuchItemException, NotReadyException {

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

    Generation generation = getCurrentGeneration();
    LongObjectMap<LongSet> knownItemIDs = generation.getKnownItemIDs();
    if (knownItemIDs == null) {
        throw new UnsupportedOperationException("No known item IDs available");
    }

    Lock knownItemLock = generation.getKnownItemLock().readLock();
    LongSet userKnownItemIDs;
    knownItemLock.lock();
    try {
        userKnownItemIDs = knownItemIDs.get(StringLongMapping.toLong(userID));
    } finally {
        knownItemLock.unlock();
    }
    if (userKnownItemIDs == null) {
        throw new NoSuchUserException(userID);
    }

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

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

        float[] features = Y.get(StringLongMapping.toLong(itemID));
        if (features == null) {
            throw new NoSuchItemException(itemID);
        }
        LongObjectMap<float[]> toFeatures;
        synchronized (userKnownItemIDs) {
            toFeatures = new LongObjectMap<float[]>(userKnownItemIDs.size());
            LongPrimitiveIterator it = userKnownItemIDs.iterator();
            while (it.hasNext()) {
                long fromItemID = it.nextLong();
                float[] fromFeatures = Y.get(fromItemID);
                toFeatures.put(fromItemID, fromFeatures);
            }
        }

        return translateToStringIDs(TopN.selectTopN(
                new RecommendedBecauseIterator(toFeatures.entrySet().iterator(), features), howMany));
    } finally {
        yLock.unlock();
    }
}

From source file:org.codehaus.wadi.core.contextualiser.SerialContextualiser.java

public boolean contextualise(Invocation invocation, Object id, Immoter immoter, boolean exclusiveOnly)
        throws InvocationException {
    Lock invocationLock = collapser.getLock(id);

    // the promotion begins here. allocate a lock and continue...
    try {//ww  w . j  a v a2s.  c om
        invocationLock.lockInterruptibly();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new InvocationException(e);
    } catch (Exception e) {
        throw new InvocationException("Could not acquire serialization lock for session " + id, e);
    }

    try {
        // whilst we were waiting for the motionLock, the session in question may have been moved back into memory 
        // somehow. before we proceed, confirm that this has not happened.
        Motable context = lockHandler.acquire(invocation, id);
        if (null != context) {
            try {
                return immoter.contextualise(invocation, id, context);
            } finally {
                lockHandler.release(invocation, context);
            }
        }

        // session was not promoted whilst we were waiting for motionLock. Continue down Contextualiser stack.
        return next.contextualise(invocation, id, immoter, exclusiveOnly);
    } finally {
        invocationLock.unlock();
    }
}

From source file:org.mule.security.oauth.BaseOAuthClientFactory.java

/**
 * Validates the object by checking that it exists at the object store and that
 * the state of the given object is consisten with the persisted state
 * /*from  w  w w  .j a va2s.  c om*/
 * @param key the key of the object at the object store
 * @param obj an instance of {@link org.mule.security.oauth.OAuth2Adapter}
 * @throws IllegalArgumentException if obj is not an instance of the type returned
 *             by {@link
 *             BaseOAuthClientFactory#getAdapterClass()}
 */
@Override
public final boolean validateObject(String key, OAuth2Adapter obj) {
    if (!this.getAdapterClass().isInstance(obj)) {
        throw new IllegalArgumentException("Invalid connector type");
    }

    OAuth2Adapter connector = (OAuth2Adapter) obj;

    Lock lock = this.getLock(key);
    lock.lock();
    try {
        if (!this.objectStore.contains(key)) {
            return false;
        }

        OAuthState state = this.retrieveOAuthState(key, true);

        if (connector.getAccessToken() == null) {
            return false;
        }

        if (!connector.getAccessToken().equals(state.getAccessToken())) {
            return false;
        }
        if (connector.getRefreshToken() == null && state.getRefreshToken() != null) {
            return false;
        }

        if (connector.getRefreshToken() != null
                && !connector.getRefreshToken().equals(state.getRefreshToken())) {
            return false;
        }
    } catch (ObjectStoreException e) {
        logger.warn("Could not validate object due to object store exception", e);
        return false;
    } finally {
        lock.unlock();
    }
    return true;
}

From source file:DemandCache.java

/**
 * Purges the cache of values that are deemed of less use to the accessor. The behavior of this
 * method depends the behavior of {@link #shouldRemove(CacheValue, float, float, float)}
 *//*ww  w  .ja va2  s . co m*/
public void purge() {
    Lock lock = theLock.writeLock();
    lock.lock();
    try {
        updateReference();
        scaleReference();
        int count = size();
        float totalSize = 0;
        float totalQuality = 0;
        for (CacheValue value : theCache.values()) {
            totalSize += theQualitizer.size(value.value);
            totalQuality += theQualitizer.quality(value.value);
        }
        totalQuality /= count;

        java.util.Iterator<CacheValue> iter = theCache.values().iterator();
        while (iter.hasNext()) {
            CacheValue next = iter.next();
            if (shouldRemove(next, totalSize, totalQuality, count))
                iter.remove();
        }
    } finally {
        lock.unlock();
    }
    thePurgeTime = System.currentTimeMillis();
}

From source file:com.gooddata.http.client.GoodDataHttpClient.java

private HttpResponse handleResponse(final HttpHost httpHost, final HttpRequest request,
        final HttpResponse originalResponse, final HttpContext context) throws IOException {
    final GoodDataChallengeType challenge = identifyGoodDataChallenge(originalResponse);
    if (challenge == GoodDataChallengeType.UNKNOWN) {
        return originalResponse;
    }/*  ww  w .  j  a v a2  s  . com*/
    EntityUtils.consume(originalResponse.getEntity());

    try {
        if (authLock.tryLock()) {
            //only one thread requiring authentication will get here.
            final Lock writeLock = rwLock.writeLock();
            writeLock.lock();
            boolean doSST = true;
            try {
                if (challenge == GoodDataChallengeType.TT && sst != null) {
                    if (refreshTt()) {
                        doSST = false;
                    }
                }
                if (doSST) {
                    sst = sstStrategy.obtainSst(httpClient, authHost);
                    if (!refreshTt()) {
                        throw new GoodDataAuthException("Unable to obtain TT after successfully obtained SST");
                    }
                }
            } catch (GoodDataAuthException e) {
                return new BasicHttpResponse(new BasicStatusLine(originalResponse.getProtocolVersion(),
                        HttpStatus.SC_UNAUTHORIZED, e.getMessage()));
            } finally {
                writeLock.unlock();
            }
        } else {
            // the other thread is performing auth and thus is holding the write lock
            // lets wait until it is finished (the write lock is granted) and then continue
            authLock.lock();
        }
    } finally {
        authLock.unlock();
    }
    return this.execute(httpHost, request, context);
}

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

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

    // Record datum
    try {/*from  w ww  .j a v  a2s.  co  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();
        }

    }

}