Example usage for java.util.concurrent ConcurrentMap putIfAbsent

List of usage examples for java.util.concurrent ConcurrentMap putIfAbsent

Introduction

In this page you can find the example usage for java.util.concurrent ConcurrentMap putIfAbsent.

Prototype

V putIfAbsent(K key, V value);

Source Link

Document

If the specified key is not already associated with a value, associates it with the given value.

Usage

From source file:org.apache.ranger.common.TestTimedExecutor.java

static void recordResult(ConcurrentMap<String, AtomicInteger> results, String key) {
    if (results.containsKey(key)) {
        results.get(key).incrementAndGet();
    } else {/*w w w  .  j  a v a 2  s  .co m*/
        AtomicInteger previous = results.putIfAbsent(key, new AtomicInteger(1));
        if (previous != null) { // a value was already associated with the key
            previous.incrementAndGet();
        }
    }
}

From source file:com.sm.store.cluster.Utils.java

public static String validateId(List<ClusterNodes> nodes) {
    StringBuilder sb = new StringBuilder();
    ConcurrentMap<Integer, Short> map = new ConcurrentHashMap<Integer, Short>(nodes.size());
    for (ClusterNodes node : nodes) {
        for (int i = 0; i < node.getPartitionArray().length; i++) {
            if (map.putIfAbsent(node.getPartitionArray()[i], node.getId()) != null)
                sb.append(" id =" + node.getId());
        }//from   www  . j  a  v  a2s .  c  om
    }
    return sb.toString();
}

From source file:org.linagora.linshare.webservice.utils.FlowUploaderUtils.java

public static java.nio.file.Path getTempFile(String identifier, ConcurrentMap<String, ChunkedFile> chunkedFiles)
        throws IOException {
    ChunkedFile chunkedFile = chunkedFiles.get(identifier);
    if (chunkedFile == null) {
        java.nio.file.Path path = Files.createTempFile("ls-chunks-" + identifier, ".temp");
        chunkedFiles.putIfAbsent(identifier, new ChunkedFile(path));
        chunkedFile = chunkedFiles.get(identifier);
    }//w w  w  . ja v a  2s. com
    return chunkedFile.getPath();
}

From source file:com.google.api.ads.adwords.jaxws.extensions.kratu.restserver.AbstractServerResource.java

@SuppressWarnings("unchecked")
static Series<Header> getMessageHeaders(Message message) {
    ConcurrentMap<String, Object> attrs = message.getAttributes();
    Series<Header> headers = (Series<Header>) attrs.get(HEADERS_KEY);
    if (headers == null) {
        headers = new Series<Header>(Header.class);
        Series<Header> prev = (Series<Header>) attrs.putIfAbsent(HEADERS_KEY, headers);
        if (prev != null) {
            headers = prev;/*  ww  w. ja v a 2s  .  c  o m*/
        }
    }
    return headers;
}

From source file:org.polymap.core.data.feature.buffer.LayerFeatureBufferManager.java

/**
 * Gets the buffer manager for the given layer of the current session. If no
 * manager exists yet a new one is created with default buffer type/impl and
 * settings if <code>create</code> is true, otherwise null might be returned.
 * /* w w w.ja  v a2  s .  c  o  m*/
 * @param layer
 * @param create True specifies that a new buffer manager is created if
 *        necessary.
 * @return The buffer manager for the given layer.
 */
public static LayerFeatureBufferManager forLayer(ILayer layer, boolean create) {
    assert layer != null;

    ConcurrentMap<String, LayerFeatureBufferManager> managers = Session.instance().managers;
    LayerFeatureBufferManager result = managers.get(layer.id());
    if (result == null && create) {
        result = new LayerFeatureBufferManager(layer);
        LayerFeatureBufferManager prev = managers.putIfAbsent(layer.id(), result);
        result = prev != null ? prev : result;
        assert result.getLayer() == layer;
    }
    return result;
}

From source file:org.grails.beans.support.CachedIntrospectionResults.java

/**
 * Create CachedIntrospectionResults for the given bean class.
 * @param beanClass the bean class to analyze
 * @return the corresponding CachedIntrospectionResults
 * @throws org.springframework.beans.BeansException in case of introspection failure
 */// ww w.j  av a  2 s.  co  m
@SuppressWarnings("unchecked")
public static CachedIntrospectionResults forClass(Class<?> beanClass) throws BeansException {
    CachedIntrospectionResults results = strongClassCache.get(beanClass);
    if (results != null) {
        return results;
    }
    results = softClassCache.get(beanClass);
    if (results != null) {
        return results;
    }

    results = new CachedIntrospectionResults(beanClass);
    ConcurrentMap<Class<?>, CachedIntrospectionResults> classCacheToUse;

    if (ClassUtils.isCacheSafe(beanClass, CachedIntrospectionResults.class.getClassLoader())
            || isClassLoaderAccepted(beanClass.getClassLoader())) {
        classCacheToUse = strongClassCache;
    } else {
        classCacheToUse = softClassCache;
    }

    CachedIntrospectionResults existing = classCacheToUse.putIfAbsent(beanClass, results);
    return (existing != null ? existing : results);
}

From source file:org.kuali.rice.krad.data.platform.MaxValueIncrementerFactory.java

/**
 * Either constructs a new incrementer or retrieves a cached instance for the given DataSource and target
 * incrementer name.//from w ww. ja va  2  s.  c  o  m
 *
 * @param dataSource the {@link DataSource} for which to retrieve the incrementer.
 * @param incrementerName the case-insensitive name of the incrementer to use, this will generally be the name of
 *        the database object which is used to implement the incrementer.
 * @return an incrementer that can be used to generate the next incremented value for the given incrementer against
 *         the specified {@link DataSource}.
 *
 * @throws IllegalArgumentException if dataSource or incrementerName are null or blank.
 */
public static DataFieldMaxValueIncrementer getIncrementer(DataSource dataSource, String incrementerName) {
    if (dataSource == null) {
        throw new IllegalArgumentException("DataSource must not be null");
    }
    if (StringUtils.isBlank(incrementerName)) {
        throw new IllegalArgumentException("Incrementer name must not be null or blank");
    }

    // yes, we want to check if it's there first, then put if absent, for max speed! This is like ConcurrentMap's
    // version of double-checked locking.
    ConcurrentMap<String, DataFieldMaxValueIncrementer> incrementerCache = cache.get(dataSource);

    if (incrementerCache == null) {
        cache.put(dataSource, new ConcurrentHashMap<String, DataFieldMaxValueIncrementer>(8, 0.9f, 1));
        if (incrementerCache == null) {
            incrementerCache = cache.get(dataSource);
        }
    }

    // now check if we have a cached incrementer
    DataFieldMaxValueIncrementer incrementer = incrementerCache.get(incrementerName.toUpperCase());
    if (incrementer == null) {
        incrementer = incrementerCache.putIfAbsent(incrementerName.toUpperCase(),
                createIncrementer(dataSource, incrementerName));
        if (incrementer == null) {
            incrementer = incrementerCache.get(incrementerName.toUpperCase());
        }
    }
    return incrementer;

}

From source file:net.yasion.common.core.bean.wrapper.CachedIntrospectionResults.java

/**
 * Create CachedIntrospectionResults for the given bean class.
 * //from w ww  .j  av  a2s . com
 * @param beanClass
 *            the bean class to analyze
 * @return the corresponding CachedIntrospectionResults
 * @throws BeansException
 *             in case of introspection failure
 */
public static CachedIntrospectionResults forClass(Class<?> beanClass) throws BeansException {
    CachedIntrospectionResults results = strongClassCache.get(beanClass);
    if (results != null) {
        return results;
    }
    results = softClassCache.get(beanClass);
    if (results != null) {
        return results;
    }

    results = new CachedIntrospectionResults(beanClass);
    ConcurrentMap<Class<?>, CachedIntrospectionResults> classCacheToUse;

    if (ClassUtils.isCacheSafe(beanClass, CachedIntrospectionResults.class.getClassLoader())
            || isClassLoaderAccepted(beanClass.getClassLoader())) {
        classCacheToUse = strongClassCache;
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Not strongly caching class [" + beanClass.getName() + "] because it is not cache-safe");
        }
        classCacheToUse = softClassCache;
    }

    CachedIntrospectionResults existing = classCacheToUse.putIfAbsent(beanClass, results);
    return (existing != null ? existing : results);
}

From source file:com.springframework.beans.CachedIntrospectionResults.java

/**
 * Create CachedIntrospectionResults for the given bean class.
 * @param beanClass the bean class to analyze
 * @return the corresponding CachedIntrospectionResults
 * @throws BeansException in case of introspection failure
 *///from   w  ww. jav a 2s .  com
@SuppressWarnings("unchecked")
static CachedIntrospectionResults forClass(Class<?> beanClass) throws BeansException {
    CachedIntrospectionResults results = strongClassCache.get(beanClass);
    if (results != null) {
        return results;
    }
    results = softClassCache.get(beanClass);
    if (results != null) {
        return results;
    }

    results = new CachedIntrospectionResults(beanClass);
    ConcurrentMap<Class<?>, CachedIntrospectionResults> classCacheToUse;

    if (ClassUtils.isCacheSafe(beanClass, CachedIntrospectionResults.class.getClassLoader())
            || isClassLoaderAccepted(beanClass.getClassLoader())) {
        classCacheToUse = strongClassCache;
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Not strongly caching class [" + beanClass.getName() + "] because it is not cache-safe");
        }
        classCacheToUse = softClassCache;
    }

    CachedIntrospectionResults existing = classCacheToUse.putIfAbsent(beanClass, results);
    return (existing != null ? existing : results);
}

From source file:org.esigate.url.RoundRobinBaseUrlRetrieveStrategyTest.java

public void testGetBaseURL() {
    String[] baseUrls = new String[] { "http://example.com/test/", "http://example1.com/test/",
            "http://example2.com/test/" };
    BaseUrlRetrieveStrategy strategy = new RoundRobinBaseUrlRetrieveStrategy(baseUrls);
    IncomingRequest request = TestUtils.createIncomingRequest().build();
    int times = 5;
    int requestsCount = baseUrls.length * times;
    ConcurrentMap<String, AtomicInteger> counterMap = new ConcurrentHashMap<String, AtomicInteger>();
    for (int i = 0; i < requestsCount; i++) {
        String baseUrl = strategy.getBaseURL(request);
        counterMap.putIfAbsent(baseUrl, new AtomicInteger(0));
        counterMap.get(baseUrl).incrementAndGet();
    }//  w ww  .j ava  2 s .  c  om
    for (String baseUrl : baseUrls) {
        assertEquals(times, counterMap.get(baseUrl).get());
    }
}