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

@Override
public void setPreference(String userID, String itemID, float value) {

    // Record datum
    try {//  w  w  w .j av  a  2s  . com
        generationManager.append(userID, itemID, value);
    } 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);

    float[] userFeatures = getFeatures(longUserID, generation.getX(), generation.getXLock());

    boolean newItem;
    Lock yReadLock = generation.getYLock().readLock();
    yReadLock.lock();
    try {
        newItem = generation.getY().get(longItemID) == null;
    } finally {
        yReadLock.unlock();
    }
    if (newItem) {
        generation.getCandidateFilter().addItem(itemID);
    }

    float[] itemFeatures = getFeatures(longItemID, generation.getY(), generation.getYLock());

    updateFeatures(userFeatures, itemFeatures, value, generation);

    LongObjectMap<LongSet> knownItemIDs = generation.getKnownItemIDs();
    if (knownItemIDs != null) {
        LongSet userKnownItemIDs;
        ReadWriteLock knownItemLock = generation.getKnownItemLock();
        Lock knownItemReadLock = knownItemLock.readLock();
        knownItemReadLock.lock();
        try {
            userKnownItemIDs = knownItemIDs.get(longUserID);
            if (userKnownItemIDs == null) {
                userKnownItemIDs = new LongSet();
                Lock knownItemWriteLock = knownItemLock.writeLock();
                knownItemReadLock.unlock();
                knownItemWriteLock.lock();
                try {
                    knownItemIDs.put(longUserID, userKnownItemIDs);
                } finally {
                    knownItemReadLock.lock();
                    knownItemWriteLock.unlock();
                }
            }
        } finally {
            knownItemReadLock.unlock();
        }

        synchronized (userKnownItemIDs) {
            userKnownItemIDs.add(longItemID);
        }
    }
}

From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java

/**
 * Plans an execution of the given TaskWrapper (the execution will be performed as soon
 * as a thread is available and the delay expires).
 * <p>IMPORTANT NOTE: the caller must lock the task before calling this method
 * using getHandlingTaskLock to obtain a lock instance.
 * @return true if the task execution has been planned to be performed as soon as
 *         possible, false otherwise/*w  w w  .ja v a  2 s.com*/
 *         (the same task or another equal task is waiting for its execution or
 *         is already running)
 * @param newTask the task to execute
 * @param delay the delay in the execution
 */
private boolean submitTaskWrapper(TaskWrapper newTask, long delay) {

    if (newTask == null) {
        throw new IllegalArgumentException("Task must be not null");
    }

    ScheduledFuture future = null;
    TaskWrapper task = null;

    //
    // The caller must lock the task
    //
    synchronized (taskFutures) {
        future = (ScheduledFuture) taskFutures.get(newTask);
        task = (TaskWrapper) taskFutures.getKey(future);
    }

    //
    // Task null means that in taskFutures there is not the task yet (first
    // execution ?)
    //
    if (task == null) {
        task = newTask;
    } else {
        //
        // There is already an equals task in the taskFutures map. We try
        // to force queue a new execution
        //
        boolean queued = false;

        queued = task.queueNewExecution();

        if (queued) {
            if (log.isTraceEnabled()) {
                log.trace("Execution of '" + task + "' queued");
            }
            return false;
        }

    }

    //
    // We use the execution lock to avoid the task execution before putting
    // it in the taskFutures map.
    // See TaskWrapper.execute
    //
    Lock taskExecutionLock = new ReentrantLock();
    taskExecutionLock.lock();
    try {
        task.setExecutionLock(taskExecutionLock);

        future = schedule(task, delay, TimeUnit.MILLISECONDS);

        synchronized (taskFutures) {
            taskFutures.put(task, future);
        }
    } finally {
        taskExecutionLock.unlock();
    }
    return true;
}

From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java

/**
 * Cancels execution of the task identified by the given id and removes its
 * scheduled execution//from w ww. j a  va2  s . c  om
 * @param taskId the id of task to stop/remove
 * @param mayInterruptIfRunning true if the thread executing this task should
 *        be interrupted; otherwise, in-progress tasks are allowed to complete
 * @return true if the task has been removed successfully, false otherwise (for instance
 *         if the task doesn't exist)
 */
public boolean removeScheduledTask(long taskId, boolean mayInterruptIfRunning) {

    ScheduledTaskWrapper dummyTask = new ScheduledTaskWrapper(taskId);

    if (log.isTraceEnabled()) {
        log.trace("Removing task '" + taskId + "'");
    }
    //
    // Locking the lock for this task so no other thread can handle it avoiding
    // conflict (what happens if a thread is removing it an another threead is
    // updating it ?)
    //
    Lock handlingTaskLock = getHandlingTaskLock(taskId);
    handlingTaskLock.lock();
    try {
        ScheduledFuture scheduledFuture = null;
        ScheduledTaskWrapper scheduledTask = null;

        synchronized (scheduledFutures) {
            scheduledFuture = (ScheduledFuture) scheduledFutures.get(dummyTask);
            scheduledTask = (ScheduledTaskWrapper) scheduledFutures.getKey(scheduledFuture);
        }

        if (scheduledFuture != null) {

            scheduledFuture.cancel(mayInterruptIfRunning);

            if (scheduledTask != null) {
                try {
                    scheduledTask.shutdown();
                } catch (TaskException ex) {
                    log.error("Error shutting down scheduled task '" + scheduledTask + "'", ex);
                }
                scheduledTask.setState(ScheduledTaskWrapper.State.SHUTDOWN);
            }

            synchronized (scheduledFutures) {
                //
                // Any time we remove the scheduledTask from scheduledFutures,
                // we try to remove the scheduledFuture from the queue. This
                // is not really needed because after a while this is performed
                // automatically but in this way we keep scheduledFutures and
                // the queue in sync
                //
                if (scheduledFuture instanceof Runnable) {
                    super.remove((Runnable) scheduledFuture);
                }
                scheduledFutures.remove(scheduledTask);
            }

            if (log.isTraceEnabled()) {
                log.trace("Task '" + taskId + "' cancelled successfully");
            }
            return true;

        } else {
            if (log.isTraceEnabled()) {
                log.trace("Task '" + taskId + "' seems not scheduled");
            }
            return false;
        }
    } finally {
        handlingTaskLock.unlock();
    }
}

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  w  w .  j av a  2 s. c o m
 * @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:jp.aegif.nemaki.cmis.service.impl.ObjectServiceImpl.java

@Override
public List<RenditionData> getRenditions(CallContext callContext, String repositoryId, String objectId,
        String renditionFilter, BigInteger maxItems, BigInteger skipCount, ExtensionsData extension) {

    Lock lock = threadLockService.getReadLock(repositoryId, objectId);
    try {//from w  w w  . j  ava  2 s. c o m
        lock.lock();

        List<Rendition> renditions = contentService.getRenditions(repositoryId, objectId);

        List<RenditionData> results = new ArrayList<RenditionData>();
        for (Rendition rnd : renditions) {
            RenditionDataImpl data = new RenditionDataImpl(rnd.getId(), rnd.getMimetype(),
                    BigInteger.valueOf(rnd.getLength()), rnd.getKind(), rnd.getTitle(),
                    BigInteger.valueOf(rnd.getWidth()), BigInteger.valueOf(rnd.getHeight()),
                    rnd.getRenditionDocumentId());
            results.add(data);
        }
        return results;
    } finally {
        lock.unlock();
    }
}

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

@Override
public AllowableActions getAllowableActions(CallContext callContext, String repositoryId, String objectId) {

    exceptionService.invalidArgumentRequired("objectId", objectId);

    Lock lock = threadLockService.getReadLock(repositoryId, objectId);

    try {/*from w  w w.j a  va  2s. c  om*/
        lock.lock();

        // //////////////////
        // General Exception
        // //////////////////
        Content content = contentService.getContent(repositoryId, objectId);
        exceptionService.objectNotFound(DomainType.OBJECT, content, objectId);
        // NOTE: The permission key doesn't exist according to CMIS
        // specification.

        // //////////////////
        // Body of the method
        // //////////////////
        return compileService.compileAllowableActions(callContext, repositoryId, content);

    } finally {
        lock.unlock();
    }
}

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

@Override
public ContentStream getContentStream(CallContext callContext, String repositoryId, String objectId,
        String streamId, BigInteger offset, BigInteger length) {

    exceptionService.invalidArgumentRequired("objectId", objectId);

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

        // //////////////////
        // General Exception
        // //////////////////
        Content content = contentService.getContent(repositoryId, objectId);
        exceptionService.objectNotFound(DomainType.OBJECT, content, objectId);
        exceptionService.permissionDenied(callContext, repositoryId,
                PermissionMapping.CAN_GET_PROPERTIES_OBJECT, content);

        // //////////////////
        // Body of the method
        // //////////////////
        if (streamId == null) {
            return getContentStreamInternal(repositoryId, content, offset, length);
        } else {
            return getRenditionStream(repositoryId, content, streamId);
        }
    } finally {
        lock.unlock();
    }
}

From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java

/**
 * Updates the task stopping it and rescheduling it
 * @param task the task to update// w  w w. ja v a  2s .c om
 */
public void updateScheduledTask(ScheduledTaskWrapper task) {
    if (task == null) {
        if (log.isTraceEnabled()) {
            log.trace("Trying to update a null task. Request rejected");
        }
        return;
    }
    if (log.isInfoEnabled()) {
        log.info("Updating task '" + task + "'. The task will be cancelled and " + "then re-scheduled");
    }
    //
    // Locking the lock for this task so no other thread can handle it avoiding
    // conflict (what happens if a thread is removing it an another threead is
    // updating it ?)
    //
    Lock handlingTaskLock = getHandlingTaskLock(task.getId());
    handlingTaskLock.lock();
    try {
        ScheduledFuture scheduledFuture = null;
        ScheduledTaskWrapper oldScheduledTask = null;

        synchronized (scheduledFutures) {
            scheduledFuture = (ScheduledFuture) scheduledFutures.get(task);
            oldScheduledTask = (ScheduledTaskWrapper) scheduledFutures.getKey(scheduledFuture);
        }

        boolean cancelled = false;
        if (scheduledFuture != null) {
            cancelled = scheduledFuture.isCancelled();
            if (!cancelled) {
                cancelled = scheduledFuture.cancel(true); // if we can, we stop its
                                                          // execution. Remember that
                                                          // cancel means cancel its
                                                          // scheduled execution and
                                                          // not just the running one
                if (cancelled) {
                    if (log.isTraceEnabled()) {
                        log.trace("Task '" + task.getId() + "' cancelled successfully");
                    }
                } else {
                    if (log.isTraceEnabled()) {
                        log.trace("Task '" + task.getId() + "' not cancelled for unknown reasons."
                                + "Is it already cancelled ? "
                                + ((scheduledFuture.isCancelled() ? "YES" : "NO")));
                    }
                }

            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Task '" + task.getId() + "' has been already cancelled");
                }
            }
            if (!ScheduledTaskWrapper.State.SHUTDOWN.equals(oldScheduledTask.getState())) {
                if (log.isTraceEnabled()) {
                    log.trace("Shutting down task '" + task.getId() + "'");
                }
                try {
                    oldScheduledTask.shutdown();
                } catch (TaskException ex) {
                    log.error("Error shutting down scheduled task '" + oldScheduledTask + "'", ex);
                }
                oldScheduledTask.setState(ScheduledTaskWrapper.State.SHUTDOWN);
            }

            synchronized (scheduledFutures) {
                //
                // Any time we remove the scheduledTask from scheduledFutures,
                // we try to remove the scheduledFuture from the queue. This
                // is not really needed because after a while this is performed
                // automatically but in this way we keep scheduledFutures and
                // the queue in sync
                //
                if (scheduledFuture instanceof Runnable) {
                    super.remove((Runnable) scheduledFuture);
                }
                scheduledFutures.remove(oldScheduledTask);
            }

        } else {
            if (log.isTraceEnabled()) {
                log.trace("Task '" + task + "' seems not scheduled");
            }
        }
        scheduleTask(task, 0);
    } finally {
        handlingTaskLock.unlock();
    }
}

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

@Override
public ObjectData getObjectByPath(CallContext callContext, String repositoryId, String path, String filter,
        Boolean includeAllowableActions, IncludeRelationships includeRelationships, String renditionFilter,
        Boolean includePolicyIds, Boolean includeAcl, ExtensionsData extension) {
    // //////////////////
    // General Exception
    // //////////////////
    exceptionService.invalidArgumentRequired("objectId", path);
    // FIXME path is not preserved in db.
    Content content = contentService.getContentByPath(repositoryId, path);

    // TODO create objectNotFoundByPath method
    exceptionService.objectNotFoundByPath(DomainType.OBJECT, content, path);

    Lock lock = threadLockService.getReadLock(repositoryId, content.getId());
    try {//from   w w  w  .j  a  v  a2s.c om
        lock.lock();

        exceptionService.permissionDenied(callContext, repositoryId,
                PermissionMapping.CAN_GET_PROPERTIES_OBJECT, content);

        // //////////////////
        // Body of the method
        // //////////////////
        return compileService.compileObjectData(callContext, repositoryId, content, filter,
                includeAllowableActions, includeRelationships, renditionFilter, includeAcl);
    } finally {
        lock.unlock();
    }
}

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 {// www  .  java2 s  .c  om
        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();
    }
}