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.ml.serving.als.model.ALSServingModel.java

void addKnownItems(String user, Collection<String> items) {
    ObjSet<String> knownItemsForUser = doGetKnownItems(user);

    if (knownItemsForUser == null) {
        Lock writeLock = xLock.writeLock();
        writeLock.lock();
        try {//from  www  .j  ava2s  . c o m
            // Check again
            knownItemsForUser = knownItems.get(user);
            if (knownItemsForUser == null) {
                knownItemsForUser = HashObjSets.newMutableSet();
                knownItems.put(user, knownItemsForUser);
            }
        } finally {
            writeLock.unlock();
        }
    }

    synchronized (knownItemsForUser) {
        knownItemsForUser.addAll(items);
    }
}

From source file:com.cloudera.oryx.ml.serving.als.model.ALSServingModel.java

/**
 * Prunes the set of items in the model, by retaining only items that are expected to appear
 * in the upcoming model updates, or, that have arrived recently. This also clears the
 * recent known items data structure.//from  ww  w .  ja  va  2s  .  co  m
 *
 * @param items items that should be retained, which are coming in the new model updates
 */
void pruneY(Collection<String> items) {
    for (int partition = 0; partition < Y.length; partition++) {
        // Keep all items in the new model, or, that have been added since last model
        Lock lock = yLocks[partition].writeLock();
        lock.lock();
        try {
            Y[partition].removeIf(new KeyOnlyBiPredicate<>(new AndPredicate<>(new NotContainsPredicate<>(items),
                    new NotContainsPredicate<>(recentNewItems[partition]))));
            recentNewItems[partition].clear();
        } finally {
            lock.unlock();
        }
    }
}

From source file:DemandCache.java

/**
 * Performs an access operation on a cache item, causing it to live longer in the cache
 * /*from ww w . j  a  v a  2s .  c om*/
 * @param key The key of the item to access
 * @param weight The weight of the access--higher weight will result in a more persistent cache
 *        item. 1-10 are supported. A guideline is that the cache item will survive longer by
 *        {@link #getHalfLife()} <code>weight</code>.
 * @see #ACCESS_GET
 * @see #ACCESS_SET
 */
public void access(K key, int weight) {
    Lock lock = theLock.readLock();
    lock.lock();
    try {
        CacheValue value = theCache.get(key);
        if (value != null)
            _access(value, weight);
    } finally {
        lock.unlock();
    }
}

From source file:com.cloudera.oryx.ml.serving.als.model.ALSServingModel.java

public Solver getYTYSolver() {
    RealMatrix YTY = null;/*w w w. ja  v  a 2 s  .  com*/
    for (int partition = 0; partition < Y.length; partition++) {
        RealMatrix YTYpartial;
        Lock lock = yLocks[partition].readLock();
        lock.lock();
        try {
            YTYpartial = VectorMath.transposeTimesSelf(Y[partition].values());
        } finally {
            lock.unlock();
        }
        if (YTYpartial != null) {
            YTY = YTY == null ? YTYpartial : YTY.add(YTYpartial);
        }
    }
    return new LinearSystemSolver().getSolver(YTY);
}

From source file:DemandCache.java

/**
 * @return The total size of the data in this cache, according to
 *         {@link Qualitizer#size(Object)}. This value will return the same as {@link #size()}
 *         if the qualitizer was not set in the constructor.
 *///w  w  w  . j  av  a 2  s.  c o  m
public float getTotalSize() {
    Lock lock = theLock.readLock();
    lock.lock();
    try {
        float ret = 0;
        for (CacheValue value : theCache.values())
            ret += theQualitizer.size(value.value);
        return ret;
    } finally {
        lock.unlock();
    }
}

From source file:DemandCache.java

/**
 * @return The average quality of the values in this cache, according to
 *         {@link Qualitizer#quality(Object)}. This value will return 1 if the qualitizer was
 *         not set in the constructor./*from  w  w  w .  jav a  2  s .c  o  m*/
 */
public float getOverallQuality() {
    Lock lock = theLock.readLock();
    lock.lock();
    try {
        float ret = 0;
        for (CacheValue value : theCache.values())
            ret += theQualitizer.quality(value.value);
        return ret / theCache.size();
    } finally {
        lock.unlock();
    }
}

From source file:DemandCache.java

/**
 * @see java.util.Map#get(java.lang.Object)
 *///from  www  . j  a  va 2  s.  c om
public V get(Object key) {
    Lock lock = theLock.readLock();
    lock.lock();
    try {
        CacheValue value = theCache.get(key);
        if (value == null)
            return null;
        _access(value, ACCESS_GET);
        return value.value;
    } finally {
        lock.unlock();
    }
}

From source file:DemandCache.java

/**
 * @see java.util.Map#remove(java.lang.Object)
 *//*ww  w  .j  av  a2  s.c  o  m*/
public V remove(Object key) {
    Lock lock = theLock.writeLock();
    lock.lock();
    try {
        if (thePurgeTime < System.currentTimeMillis() - 60 * 1000)
            purge();
        CacheValue oldValue = theCache.remove(key);
        return oldValue == null ? null : oldValue.value;
    } finally {
        lock.unlock();
    }
}

From source file:org.ng200.openolympus.services.TestingService.java

private void checkVerdict(final Verdict verdict, final SolutionJudge judge, final List<Path> testFiles,
        final BigDecimal maximumScore, final Properties properties) throws ExecutionException {
    if (this.dataProvider == null) {
        throw new IllegalStateException("Shared data provider is null!");
    }/*from w ww. jav a  2  s .c  o m*/

    final Lock lock = verdict.getSolution().getTask().readLock();
    lock.lock();

    try {
        TestingService.logger.info("Scheduling verdict {} for testing.", verdict.getId());

        final JPPFJob job = new JPPFJob();
        job.setDataProvider(this.dataProvider);

        job.setName("Check verdict " + verdict.getId());

        final int priority = (int) ((verdict.isViewableWhenContestRunning() ? (Integer.MAX_VALUE / 2) : 0)
                - verdict.getId());
        job.getSLA().setMaxNodes(1);
        job.getSLA().setPriority(priority);
        job.getSLA().setDispatchExpirationSchedule(new JPPFSchedule(60000L));
        job.getSLA().setMaxDispatchExpirations(3);

        TaskContainer taskContainer = taskContainerCache
                .getTaskContainerForTask(verdict.getSolution().getTask());

        Thread.currentThread().setContextClassLoader(
                new URLClassLoader(taskContainer.getClassLoaderURLs().toArray(new URL[0]),
                        Thread.currentThread().getContextClassLoader()));

        job.add(new JacksonSerializationDelegatingTask<>(
                new VerdictCheckingTask(judge, testFiles, maximumScore, properties),
                taskContainer.getClassLoaderURLs()));

        job.setBlocking(true);

        jppfClient.registerClassLoader(taskContainer.getClassLoader(), job.getUuid());
        this.jppfClient.submitJob(job);
        @SuppressWarnings("unchecked")
        final org.jppf.node.protocol.Task<String> task = (org.jppf.node.protocol.Task<String>) job
                .awaitResults().get(0);

        if (task.getThrowable() != null) {
            throw task.getThrowable();
        }

        ObjectMapper objectMapper = JacksonSerializationFactory.createObjectMapper();

        final JsonTaskExecutionResult<Pair<SolutionJudge, SolutionResult>> checkingResult = ((JacksonSerializationDelegatingTask<Pair<SolutionJudge, SolutionResult>, VerdictCheckingTask>) job
                .awaitResults().get(0)).getResultOrThrowable();

        if (checkingResult.getError() != null) {
            throw checkingResult.getError();
        }

        final SolutionResult result = checkingResult.getResult().getSecond();

        verdict.setScore(result.getScore());
        verdict.setMemoryPeak(result.getMemoryPeak());
        verdict.setCpuTime(Duration.ofMillis(result.getCpuTime()));
        verdict.setRealTime(Duration.ofMillis(result.getRealTime()));

        verdict.setStatus(result.getResult());
        switch (result.getResult()) {
        case OK:
        case TIME_LIMIT:
        case MEMORY_LIMIT:
        case OUTPUT_LIMIT:
        case PRESENTATION_ERROR:
        case WRONG_ANSWER:
        case RUNTIME_ERROR:
            break;
        case INTERNAL_ERROR:
            result.getErrorMessages()
                    .forEach((stage, message) -> this.internalErrors.put(this.internalErrorCounter++,
                            new Pair<String, String>(verdict.getSolution().getTask().getName(), message)));
            break;
        case SECURITY_VIOLATION:
            verdict.setUnauthorisedSyscall(result.getUnauthorisedSyscall());
            break;
        case COMPILE_ERROR:
            final String message = result.getErrorMessages().values().stream()
                    .collect(Collectors.joining("\n"));
            verdict.setAdditionalInformation(
                    HtmlUtils.htmlEscape(message.substring(0, Math.min(128, message.length()))));
            break;
        case WAITING:
            throw new IllegalStateException("Judge returned result \"waiting\".");
        }

    } catch (final Throwable throwable) {
        verdict.setStatus(SolutionResult.Result.INTERNAL_ERROR);
        throw new RuntimeException("Couldn't run solution: ", throwable);
    } finally {
        lock.unlock();

        verdict.setTested(true);
        if (verdict.getStatus() == SolutionResult.Result.WAITING) {
            verdict.setStatus(SolutionResult.Result.INTERNAL_ERROR);
            TestingService.logger.error(
                    "Judge for task {} did not set the result status to an acceptable value: got WAITING instead.",
                    verdict.getSolution().getTask().getId());
        }
        this.solutionService.saveVerdict(verdict);
    }
}

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

private static float[] getFeatures(long id, FastByIDMap<float[]> matrix, ReadWriteLock lock) {
    float[] features;
    Lock readLock = lock.readLock();
    readLock.lock();
    try {/*w  w  w.j a  v a2 s .  co  m*/
        features = matrix.get(id);
        if (features == null) {
            int numFeatures = countFeatures(matrix);
            if (numFeatures > 0) {
                features = new float[numFeatures];
                Lock writeLock = lock.writeLock();
                readLock.unlock();
                writeLock.lock();
                try {
                    matrix.put(id, features);
                } finally {
                    readLock.lock();
                    writeLock.unlock();
                }
            }
        }
    } finally {
        readLock.unlock();
    }
    return features;
}