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:org.codehaus.wadi.location.partitionmanager.local.LocalPartitionEvacuateIMToPMAction.java

public void onMessage(Envelope message, EvacuateIMToPM request) {
    Peer newPeer = request.getPeer();//from w ww.  ja  v  a 2s  .c om
    Object key = request.getId();
    Location location;
    synchronized (nameToLocation) {
        location = (Location) nameToLocation.get(key);
    }
    boolean success = false;
    Peer oldPeer = null;
    if (location == null) {
        log.warn("evacuate [" + key + "]@[" + newPeer + "] failed; key not in use");
    } else {
        Lock lock = location.getExclusiveLock();
        try {
            lock.lockInterruptibly();
            try {
                oldPeer = location.getSMPeer();
                if (oldPeer == newPeer) {
                    log.warn("evacuate [" + key + "]@[" + newPeer + "] failed; evacuee is already there");
                } else {
                    location.setPeer(newPeer);
                    if (log.isDebugEnabled()) {
                        log.debug("evacuate [" + request.getId() + "] [" + oldPeer + "]->[" + newPeer + "]");
                    }
                    success = true;
                }
            } finally {
                lock.unlock();
            }
        } catch (InterruptedException e) {
            log.error("unexpected interruption waiting to perform relocation: " + key, e);
            Thread.currentThread().interrupt();
        }
    }

    SessionResponseMessage response = new EvacuatePMToIM(success);
    try {
        dispatcher.reply(message, response);
    } catch (MessageExchangeException e) {
        log.warn("See exception", e);
    }
}

From source file:org.apache.bookkeeper.bookie.EntryLogManagerForEntryLogPerLedger.java

@Override
public long addEntry(long ledger, ByteBuf entry, boolean rollLog) throws IOException {
    Lock lock = getLock(ledger);
    lock.lock();//from w  ww . ja v  a2  s .  c  o m
    try {
        return super.addEntry(ledger, entry, rollLog);
    } finally {
        lock.unlock();
    }
}

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 a  2 s  .co m*/
 */
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:DemandCache.java

/**
 * @see java.util.Map#keySet()//from ww w. ja  v a 2  s.c  om
 */
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:com.mastfrog.netty.http.client.CookieStore.java

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

From source file:org.mule.service.oauth.internal.AbstractOAuthDancer.java

/**
 * Retrieves the oauth context for a particular user. If there's no state for that user a new state is retrieve so never returns
 * null./*from   ww w .jav  a  2s  . c o  m*/
 *
 * @param resourceOwnerId id of the user.
 * @return oauth state
 */
public ResourceOwnerOAuthContext getContextForResourceOwner(String resourceOwnerId) {
    if (resourceOwnerId == null) {
        resourceOwnerId = DEFAULT_RESOURCE_OWNER_ID;
    }

    final String transformedResourceOwnerId = resourceOwnerIdTransformer.apply(resourceOwnerId);

    DefaultResourceOwnerOAuthContext resourceOwnerOAuthContext = null;
    if (!tokensStore.containsKey(transformedResourceOwnerId)) {
        final Lock lock = lockProvider.createLock(toString() + "-config-oauth-context");
        lock.lock();
        try {
            if (!tokensStore.containsKey(transformedResourceOwnerId)) {
                resourceOwnerOAuthContext = new DefaultResourceOwnerOAuthContext(
                        createLockForResourceOwner(transformedResourceOwnerId), resourceOwnerId);
                tokensStore.put(transformedResourceOwnerId, resourceOwnerOAuthContext);
            }
        } finally {
            lock.unlock();
        }
    }
    if (resourceOwnerOAuthContext == null) {
        resourceOwnerOAuthContext = tokensStore.get(transformedResourceOwnerId);
        resourceOwnerOAuthContext
                .setRefreshUserOAuthContextLock(createLockForResourceOwner(transformedResourceOwnerId));
    }
    return resourceOwnerOAuthContext;
}

From source file:org.orbeon.oxf.cache.MemoryCacheImpl.java

private boolean tryEvict(CacheEntry entry) {

    assert keyToEntryMap.containsKey(entry.key);

    // Obtain lock if possible
    final Lock lock;
    final boolean canEvict;
    if (entry.cacheable instanceof Cacheable) {
        lock = ((Cacheable) entry.cacheable).getEvictionLock();
        canEvict = lock == null || lock.tryLock();
    } else {//w  ww .  j a  v  a2 s  .co  m
        lock = null;
        canEvict = true;
    }

    // Only remove object if we are allowed to
    if (canEvict) {
        try {
            remove(entry.key, true, false);
        } finally {
            // Release lock if we got one
            if (lock != null)
                lock.unlock();
        }
    }

    return canEvict;
}

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

/**
 * wait until the goal buffer isn't empty
 * /* www. j  a va 2 s .  co 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:DemandCache.java

/**
 * @see java.util.Map#remove(java.lang.Object)
 *///from   w w w  . j a v  a  2  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:com.mastfrog.netty.http.client.CookieStore.java

public String toString() {
    Lock readLock = lock.readLock();
    List<Cookie> cks = new ArrayList<Cookie>();
    readLock.lock();//from  w  ww.ja  v a 2  s  .  c om
    try {
        if (cookies.isEmpty()) {
            return "[no cookies]";
        }
        cks.addAll(cookies);
    } finally {
        readLock.unlock();
    }
    Collections.sort(cks);
    return Headers.COOKIE.toString(cks.toArray(new Cookie[cks.size()]));
}