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:DemandCache.java

/**
 * @see java.util.Map#put(java.lang.Object, java.lang.Object)
 *//*from  w w  w  .  j  ava 2  s .  c o m*/
public V put(K key, V value) {
    Lock lock = theLock.writeLock();
    lock.lock();
    try {
        if (thePurgeTime < System.currentTimeMillis() - 60 * 1000)
            purge();
        CacheValue newValue = new CacheValue();
        newValue.value = value;
        _access(newValue, ACCESS_SET);
        CacheValue oldValue = theCache.put(key, newValue);
        return oldValue == null ? null : oldValue.value;
    } finally {
        lock.unlock();
    }
}

From source file:DemandCache.java

/**
 * @see java.util.Map#putAll(java.util.Map)
 *//*from   w  ww  .  j  a  v a2s .c  o m*/
public void putAll(Map<? extends K, ? extends V> m) {
    Lock lock = theLock.writeLock();
    lock.lock();
    try {
        if (thePurgeTime < System.currentTimeMillis() - 60 * 1000)
            purge();
        for (java.util.Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
            CacheValue cv = new CacheValue();
            cv.value = entry.getValue();
            _access(cv, ACCESS_SET);
            theCache.put(entry.getKey(), cv);
        }
    } finally {
        lock.unlock();
    }
}

From source file:org.apache.stratos.common.clustering.impl.HazelcastDistributedObjectProvider.java

/**
 * Acquires a distributed lock if clustering is enabled, else acquires a local reentrant lock and
 * returns the lock object./*  w  w w  . java2s. com*/
 *
 * @param object
 * @return
 */
@Override
public Lock acquireLock(Object object) {
    if (isClustered()) {
        return acquireDistributedLock(object);
    } else {
        Lock lock = locksMap.get(object);
        if (lock == null) {
            synchronized (object) {
                if (lock == null) {
                    lock = new ReentrantLock();
                    locksMap.put(object, lock);
                }
            }
        }
        lock.lock();
        return lock;
    }
}

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

public List<Pair<String, float[]>> getKnownItemVectorsForUser(String user) {
    float[] userVector = getUserVector(user);
    if (userVector == null) {
        return null;
    }//from  w ww .j a  va 2s. c  o m
    Collection<String> knownItems = getKnownItems(user);
    if (knownItems == null || knownItems.isEmpty()) {
        return null;
    }
    List<Pair<String, float[]>> idVectors = new ArrayList<>(knownItems.size());
    synchronized (knownItems) {
        for (String itemID : knownItems) {
            int partition = partition(itemID);
            float[] vector;
            Lock lock = yLocks[partition].readLock();
            lock.lock();
            try {
                vector = Y[partition].get(itemID);
            } finally {
                lock.unlock();
            }
            idVectors.add(new Pair<>(itemID, vector));
        }
    }
    return idVectors;
}

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)}
 *///  w w  w . j a v  a 2 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.cloudera.oryx.ml.serving.als.model.ALSServingModel.java

/**
 * Like {@link #pruneX(Collection)} and {@link #pruneY(Collection)} but prunes the
 * known-items data structure.//w  w w  .j  a v a2s .c om
 */
void pruneKnownItems(Collection<String> users, final Collection<String> items) {
    // Keep all users in the new model, or, that have been added since last model
    Lock xWriteLock = xLock.writeLock();
    xWriteLock.lock();
    try {
        knownItems.removeIf(new KeyOnlyBiPredicate<>(new AndPredicate<>(new NotContainsPredicate<>(users),
                new NotContainsPredicate<>(recentNewUsers))));
    } finally {
        xWriteLock.unlock();
    }

    // This will be easier to quickly copy the whole (smallish) set rather than
    // deal with locks below
    final Collection<String> allRecentKnownItems = new HashSet<>();
    for (int partition = 0; partition < Y.length; partition++) {
        Lock yWriteLock = yLocks[partition].writeLock();
        yWriteLock.lock();
        try {
            allRecentKnownItems.addAll(recentNewItems[partition]);
        } finally {
            yWriteLock.unlock();
        }
    }

    Lock xReadLock = xLock.readLock();
    xReadLock.lock();
    try {
        for (ObjSet<String> knownItemsForUser : knownItems.values()) {
            synchronized (knownItemsForUser) {
                knownItemsForUser.removeIf(new Predicate<String>() {
                    @Override
                    public boolean test(String value) {
                        return !items.contains(value) && !allRecentKnownItems.contains(value);
                    }
                });
            }
        }
    } finally {
        xReadLock.unlock();
    }
}

From source file:org.grails.datastore.mapping.gemfire.engine.GemfireEntityPersister.java

@Override
public Object lock(final Serializable id) throws CannotAcquireLockException {
    final GemfireTemplate template = gemfireDatastore.getTemplate(getPersistentEntity());

    return template.execute(new GemfireCallback() {
        public Object doInGemfire(Region region) throws GemFireCheckedException, GemFireException {
            final Lock lock = region.getDistributedLock(id);
            lock.lock();
            final Object o = region.get(id);
            distributedLocksHeld.put(o, lock);
            return o;
        }//from   www  .j av  a2 s  . c o  m
    });
}

From source file:DemandCache.java

/**
 * @see java.util.Map#keySet()/*from w w  w.ja  v a 2s . c  o m*/
 */
public Set<K> keySet() {
    Lock lock = theLock.writeLock();
    lock.lock();
    final Object[] keys;
    try {
        if (thePurgeTime < System.currentTimeMillis() - 60 * 1000)
            purge();
        keys = theCache.keySet().toArray();
    } finally {
        lock.unlock();
    }
    return new java.util.AbstractSet<K>() {
        @Override
        public java.util.Iterator<K> iterator() {
            return new java.util.Iterator<K>() {
                private int index = 0;

                public boolean hasNext() {
                    return index < keys.length;
                }

                public K next() {
                    index++;
                    return (K) keys[index - 1];
                }

                public void remove() {
                    DemandCache.this.remove(keys[index - 1]);
                }
            };
        }

        @Override
        public int size() {
            return keys.length;
        }
    };
}

From source file:org.jactr.core.production.action.SleepAction.java

/**
 * wait until the goal buffer isn't empty
 * /*  w  w  w. java2s . c o m*/
 * @see org.jactr.core.production.action.IAction#fire(org.jactr.core.production.IInstantiation, double)
 */
public double fire(IInstantiation instantiation, double firingTime) {
    IActivationBuffer goalBuffer = instantiation.getModel().getActivationBuffer(IActivationBuffer.GOAL);

    if (goalBuffer.getSourceChunk() == null) {
        final Lock goalLock = new ReentrantLock();
        final Condition gotAGoal = goalLock.newCondition();

        /*
         * merely signal when the goal buffer gets something
         */
        IActivationBufferListener listener = new ActivationBufferListenerAdaptor() {
            @Override
            public void sourceChunkAdded(ActivationBufferEvent event) {
                try {
                    goalLock.lock();
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("Signaling goal insertion");
                    gotAGoal.signalAll();
                } finally {
                    goalLock.unlock();
                }
            }
        };

        /*
         * attach the listener with the inline executor - this ensures that
         * regardless of what thread adds the source chunk to the buffer we will
         * be notified
         */
        goalBuffer.addListener(listener, ExecutorServices.INLINE_EXECUTOR);

        try {
            goalLock.lock();
            while (goalBuffer.getSourceChunk() == null) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("Waiting for goal");
                gotAGoal.await();
            }
        } catch (Exception e) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Could not wait for goal ", e);
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Resuming from wait");

        goalLock.unlock();

        /*
         * remove the listener
         */
        goalBuffer.removeListener(listener);
    } else if (LOGGER.isDebugEnabled())
        LOGGER.debug("Goal is already present, no need to sleep");

    return 0;
}

From source file:com.mastfrog.netty.http.client.CookieStore.java

public String get(String name) {
    Lock readLock = lock.readLock();
    readLock.lock();
    try {//from  w ww .  j  a  v a  2  s . co  m
        for (Cookie ck : cookies) {
            if (name.equals(ck.getName())) {
                return ck.getValue();
            }
        }
    } finally {
        readLock.unlock();
    }
    return null;
}