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:edu.internet2.middleware.shibboleth.common.attribute.resolver.provider.ShibbolethAttributeResolver.java

/** {@inheritDoc} */
public Map<String, BaseAttribute> resolveAttributes(SAMLProfileRequestContext attributeRequestContext)
        throws AttributeResolutionException {
    ShibbolethResolutionContext resolutionContext = new ShibbolethResolutionContext(attributeRequestContext);

    log.debug("{} resolving attributes for principal {}", getId(), attributeRequestContext.getPrincipalName());

    if (getAttributeDefinitions().size() == 0) {
        log.debug("No attribute definitions loaded in {} so no attributes can be resolved for principal {}",
                getId(), attributeRequestContext.getPrincipalName());
        return new HashMap<String, BaseAttribute>();
    }//from   w  w w.  ja v a  2 s  .  co  m

    Lock readLock = getReadWriteLock().readLock();
    readLock.lock();
    Map<String, BaseAttribute> resolvedAttributes = null;
    try {
        resolvedAttributes = resolveAttributes(resolutionContext);
        cleanResolvedAttributes(resolvedAttributes, resolutionContext);
    } finally {
        readLock.unlock();
    }

    log.debug(getId() + " resolved, for principal {}, the attributes: {}",
            attributeRequestContext.getPrincipalName(), resolvedAttributes.keySet());
    return resolvedAttributes;
}

From source file:edu.internet2.middleware.shibboleth.common.attribute.resolver.provider.ShibbolethAttributeResolver.java

/**
 * Resolves the attributes requested in the resolution context or all attributes if no specific attributes were
 * requested. This method does not remove dependency only attributes or attributes that do not contain values.
 * //  ww w . j  a  v  a 2  s . co m
 * @param resolutionContext current resolution context
 * 
 * @return resolved attributes
 * 
 * @throws AttributeResolutionException thrown if the attributes could not be resolved
 */
protected Map<String, BaseAttribute> resolveAttributes(ShibbolethResolutionContext resolutionContext)
        throws AttributeResolutionException {
    Collection<String> attributeIDs = resolutionContext.getAttributeRequestContext()
            .getRequestedAttributesIds();
    Map<String, BaseAttribute> resolvedAttributes = new HashMap<String, BaseAttribute>();

    // if no attributes requested, then resolve everything
    if (attributeIDs == null || attributeIDs.isEmpty()) {
        log.debug("Specific attributes for principal {} were not requested, resolving all attributes.",
                resolutionContext.getAttributeRequestContext().getPrincipalName());
        attributeIDs = getAttributeDefinitions().keySet();
    }

    Lock readLock = getReadWriteLock().readLock();
    readLock.lock();
    try {
        for (String attributeID : attributeIDs) {
            BaseAttribute resolvedAttribute = resolveAttribute(attributeID, resolutionContext);
            if (resolvedAttribute != null) {
                resolvedAttributes.put(resolvedAttribute.getId(), resolvedAttribute);
            }
        }
    } finally {
        readLock.unlock();
    }

    return resolvedAttributes;
}

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

public List<Pair<String, Double>> topN(final DoubleFunction<float[]> scoreFn, final int howMany,
        final Predicate<String> allowedPredicate) {

    List<Callable<Iterable<Pair<String, Double>>>> tasks = new ArrayList<>(Y.length);
    for (int partition = 0; partition < Y.length; partition++) {
        final int thePartition = partition;
        tasks.add(new LoggingCallable<Iterable<Pair<String, Double>>>() {
            @Override//from  ww w .j av  a2 s  .c o  m
            public Iterable<Pair<String, Double>> doCall() {
                Queue<Pair<String, Double>> topN = new PriorityQueue<>(howMany + 1,
                        PairComparators.<Double>bySecond());
                TopNConsumer topNProc = new TopNConsumer(topN, howMany, scoreFn, allowedPredicate);

                Lock lock = yLocks[thePartition].readLock();
                lock.lock();
                try {
                    Y[thePartition].forEach(topNProc);
                } finally {
                    lock.unlock();
                }
                // Ordering and excess items don't matter; will be merged and finally sorted later
                return topN;
            }
        });
    }

    List<Iterable<Pair<String, Double>>> iterables = new ArrayList<>();
    if (Y.length >= 2) {
        try {
            for (Future<Iterable<Pair<String, Double>>> future : executor.invokeAll(tasks)) {
                iterables.add(future.get());
            }
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        } catch (ExecutionException e) {
            throw new IllegalStateException(e.getCause());
        }
    } else {
        try {
            iterables.add(tasks.get(0).call());
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    return Ordering.from(PairComparators.<Double>bySecond()).greatestOf(Iterables.concat(iterables), howMany);
}

From source file:com.cloudera.lib.service.instrumentation.InstrumentationService.java

@SuppressWarnings("unchecked")
private <T> T getToAdd(String group, String name, Class<T> klass, Lock lock, Map<String, Map<String, T>> map) {
    boolean locked = false;
    try {/*  www.  j ava2 s  . c o m*/
        Map<String, T> groupMap = map.get(group);
        if (groupMap == null) {
            lock.lock();
            locked = true;
            groupMap = map.get(group);
            if (groupMap == null) {
                groupMap = new ConcurrentHashMap<String, T>();
                map.put(group, groupMap);
            }
        }
        T element = groupMap.get(name);
        if (element == null) {
            if (!locked) {
                lock.lock();
                locked = true;
            }
            element = groupMap.get(name);
            if (element == null) {
                try {
                    if (klass == Timer.class) {
                        element = (T) new Timer(timersSize);
                    } else {
                        element = klass.newInstance();
                    }
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
                groupMap.put(name, element);
            }
        }
        return element;
    } finally {
        if (locked) {
            lock.unlock();
        }
    }
}

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

public int size() {
    Lock readLock = lock.readLock();
    try {/*  ww  w. j  a v  a 2s .c  o  m*/
        readLock.lock();
        return cookies.size();
    } finally {
        readLock.unlock();
    }
}

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

public boolean isEmpty() {
    Lock readLock = lock.readLock();
    try {/*ww w  .  j  a va2s  .  c  o  m*/
        readLock.lock();
        return cookies.isEmpty();
    } finally {
        readLock.unlock();
    }
}

From source file:DemandCache.java

/**
 * @see java.util.Map#entrySet()// w ww.ja va2 s  .co m
 */
public Set<java.util.Map.Entry<K, V>> entrySet() {
    Lock lock = theLock.writeLock();
    lock.lock();
    final Map.Entry<K, CacheValue>[] entries;
    try {
        if (thePurgeTime < System.currentTimeMillis() - 60 * 1000)
            purge();
        entries = theCache.entrySet().toArray(new Map.Entry[0]);
    } finally {
        lock.unlock();
    }
    return new java.util.AbstractSet<Map.Entry<K, V>>() {
        @Override
        public java.util.Iterator<Map.Entry<K, V>> iterator() {
            return new java.util.Iterator<Map.Entry<K, V>>() {
                int index = 0;

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

                public Map.Entry<K, V> next() {
                    Map.Entry<K, V> ret = new Map.Entry<K, V>() {
                        private final int entryIndex = index;

                        public K getKey() {
                            return entries[entryIndex].getKey();
                        }

                        public V getValue() {
                            return entries[entryIndex].getValue().value;
                        }

                        public V setValue(V value) {
                            V retValue = entries[entryIndex].getValue().value;
                            entries[entryIndex].getValue().value = value;
                            return retValue;
                        }

                        public String toString() {
                            return entries[entryIndex].getKey().toString() + "="
                                    + entries[entryIndex].getValue().value;
                        }
                    };
                    index++;
                    return ret;
                }

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

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

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

public void remove(String name) {
    Lock writeLock = lock.writeLock();
    try {/*from   ww w . j  a  v a2 s .  c  o m*/
        writeLock.lock();
        for (Iterator<DateCookie> it = cookies.iterator(); it.hasNext();) {
            DateCookie ck = it.next();
            if (name.equals(ck.getName())) {
                it.remove();
            }
        }
    } finally {
        writeLock.unlock();
    }
}

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

void decorate(HttpRequest req) {
    URL url;/*from   w  w w.  j  av a2  s .  c  om*/
    if (!req.getUri().contains("://")) {
        String host = req.headers().get(Headers.HOST.name());
        url = URL.builder().setPath(req.getUri()).setHost(host).create();
    } else {
        url = URL.parse(req.getUri());
    }
    Lock readLock = lock.readLock();
    readLock.lock();
    try {
        List<Cookie> toSend = new ArrayList<>();
        for (Cookie cookie : cookies) {
            if (checkDomain) {
                if (cookie.getDomain() != null && !cookie.getDomain().equals(url.getHost().toString())) {
                    continue;
                }
            }
            if (checkPath) {
                String pth = cookie.getPath();
                if (pth != null) {
                    String compare = url.getPath().toStringWithLeadingSlash();
                    if (!"/".equals(pth) && !"".equals(pth) && !compare.equals(pth)
                            && !compare.startsWith(pth)) {
                        continue;
                    }
                }
            }
            toSend.add(cookie);
        }
        if (!toSend.isEmpty()) {
            for (Cookie ck : toSend) {
                String headerValue = Headers.COOKIE.toString(new Cookie[] { ck });
                req.headers().add(Headers.COOKIE.name(), headerValue);
            }
        }
    } finally {
        readLock.unlock();
    }
}

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

public void add(Cookie cookie) {
    String name = cookie.getName();
    Lock writeLock = lock.writeLock();
    try {//from w  w w.j  av  a 2 s  .c  om
        writeLock.lock();
        for (Iterator<DateCookie> it = cookies.iterator(); it.hasNext();) {
            DateCookie ck = it.next();
            if (name.equals(ck.getName())) {
                it.remove();
            } else if (ck.isExpired()) {
                it.remove();
            }
        }
        if (!cookie.isDiscard() && cookie.getMaxAge() > 0) {
            cookies.add(new DateCookie(cookie));
        }
    } finally {
        writeLock.unlock();
    }
}