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.hadoop.hbase.client.MetaCache.java

/**
 * Put a newly discovered HRegionLocation into the cache.
 * @param tableName The table name./* ww w.  j  av  a2s.  c om*/
 * @param source the source of the new location
 * @param location the new location
 */
public void cacheLocation(final TableName tableName, final ServerName source, final HRegionLocation location) {
    assert source != null;
    byte[] startKey = location.getRegionInfo().getStartKey();
    ConcurrentMap<byte[], RegionLocations> tableLocations = getTableLocations(tableName);
    RegionLocations locations = new RegionLocations(new HRegionLocation[] { location });
    RegionLocations oldLocations = tableLocations.putIfAbsent(startKey, locations);
    boolean isNewCacheEntry = (oldLocations == null);
    if (isNewCacheEntry) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Cached location: " + location);
        }
        addToCachedServers(locations);
        return;
    }

    // If the server in cache sends us a redirect, assume it's always valid.
    HRegionLocation oldLocation = oldLocations.getRegionLocation(location.getRegionInfo().getReplicaId());
    boolean force = oldLocation != null && oldLocation.getServerName() != null
            && oldLocation.getServerName().equals(source);

    // For redirect if the number is equal to previous
    // record, the most common case is that first the region was closed with seqNum, and then
    // opened with the same seqNum; hence we will ignore the redirect.
    // There are so many corner cases with various combinations of opens and closes that
    // an additional counter on top of seqNum would be necessary to handle them all.
    RegionLocations updatedLocations = oldLocations.updateLocation(location, false, force);
    if (oldLocations != updatedLocations) {
        boolean replaced = tableLocations.replace(startKey, oldLocations, updatedLocations);
        if (replaced && LOG.isTraceEnabled()) {
            LOG.trace("Changed cached location to: " + location);
        }
        addToCachedServers(updatedLocations);
    }
}

From source file:org.jtalks.jcommune.plugin.auth.poulpe.service.PoulpeAuthService.java

private void addHeaderAttribute(ClientResource clientResource, String attrName, String attrValue) {
    ConcurrentMap<String, Object> attrs = clientResource.getRequest().getAttributes();
    Series<Header> headers = (Series<Header>) attrs.get(HeaderConstants.ATTRIBUTE_HEADERS);
    if (headers == null) {
        headers = new Series<>(Header.class);
        Series<Header> prev = (Series<Header>) attrs.putIfAbsent(HeaderConstants.ATTRIBUTE_HEADERS, headers);
        if (prev != null) {
            headers = prev;//from   w ww .  j  av a 2  s  .co m
        }
    }
    headers.add(attrName, attrValue);
}

From source file:com.enonic.cms.web.portal.services.UserServicesAccessManagerImpl.java

private void initSiteRules(SiteKey site) {
    ConcurrentMap<String, AccessPermission> siteRules = new ConcurrentHashMap<String, AccessPermission>();

    String allowRules = sitePropertiesService.getSiteProperty(site,
            SitePropertyNames.HTTP_SERVICES_ALLOW_PROPERTY);
    String denyRules = sitePropertiesService.getSiteProperty(site,
            SitePropertyNames.HTTP_SERVICES_DENY_PROPERTY);
    parseAndAddRules(allowRules, AccessPermission.ALLOW, siteRules, site);
    parseAndAddRules(denyRules, AccessPermission.DENY, siteRules, site);

    siteRules.putIfAbsent(ACCESS_RULE_ALL, DEFAULT_ACCESS_RULE);

    sitesAccessRules.putIfAbsent(site, siteRules);
}

From source file:org.apache.nifi.web.security.otp.OtpService.java

/**
 * Generates a token and stores it in the specified cache.
 *
 * @param cache                     The cache
 * @param authenticationToken       The authentication
 * @return                          The one time use token
 *///from   www.j  a v  a  2 s .  c o  m
private String generateToken(final ConcurrentMap<CacheKey, String> cache,
        final OtpAuthenticationToken authenticationToken) {
    if (cache.size() >= MAX_CACHE_SOFT_LIMIT) {
        throw new IllegalStateException("The maximum number of single use tokens have been issued.");
    }

    // hash the authentication and build a cache key
    final CacheKey cacheKey = new CacheKey(hash(authenticationToken));

    // store the token unless the token is already stored which should not update it's original timestamp
    cache.putIfAbsent(cacheKey, authenticationToken.getName());

    // return the token
    return cacheKey.getKey();
}

From source file:com.googlecode.concurrentlinkedhashmap.ConcurrentMapTest.java

@Test(dataProvider = "guardedMap", expectedExceptions = NullPointerException.class)
public void putIfAbsent_withNullKey(ConcurrentMap<Integer, Integer> map) {
    map.putIfAbsent(null, 2);
}

From source file:com.googlecode.concurrentlinkedhashmap.ConcurrentMapTest.java

@Test(dataProvider = "guardedMap", expectedExceptions = NullPointerException.class)
public void putIfAbsent_withNullValue(ConcurrentMap<Integer, Integer> map) {
    map.putIfAbsent(1, null);
}

From source file:com.googlecode.concurrentlinkedhashmap.ConcurrentMapTest.java

@Test(dataProvider = "guardedMap", expectedExceptions = NullPointerException.class)
public void putIfAbsent_withNullEntry(ConcurrentMap<Integer, Integer> map) {
    map.putIfAbsent(null, null);
}

From source file:org.apache.hadoop.mapreduce.v2.app.speculate.DefaultSpeculator.java

private AtomicInteger containerNeed(TaskId taskID) {
    JobId jobID = taskID.getJobId();/*from w w  w.  ja v a  2  s.c  o  m*/
    TaskType taskType = taskID.getTaskType();

    ConcurrentMap<JobId, AtomicInteger> relevantMap = taskType == TaskType.MAP ? mapContainerNeeds
            : reduceContainerNeeds;

    AtomicInteger result = relevantMap.get(jobID);

    if (result == null) {
        relevantMap.putIfAbsent(jobID, new AtomicInteger(0));
        result = relevantMap.get(jobID);
    }

    return result;
}

From source file:com.googlecode.concurrentlinkedhashmap.ConcurrentMapTest.java

@Test(dataProvider = "guardedMap")
public void putIfAbsent(ConcurrentMap<Integer, Integer> map) {
    for (Integer i = 0; i < capacity(); i++) {
        assertThat(map.putIfAbsent(i, i), is(nullValue()));
        assertThat(map.putIfAbsent(i, 1), is(i));
        assertThat(map.get(i), is(i));/*from  w ww.  j  a va2 s  .  c  om*/
    }
    assertThat(map.size(), is(equalTo((int) capacity())));
}

From source file:com.starit.diamond.client.impl.DefaultSubscriberListener.java

/**
 * DataIDManagerListener/* w w w. j a  va2s  . c  om*/
 * 
 * @param dataId
 * @param addListeners
 */
public void addManagerListeners(String dataId, String group, String instanceId,
        List<ManagerListener> addListeners) {
    if (null == dataId || null == addListeners || null == instanceId) {
        return;
    }
    if (addListeners.size() == 0) {
        return;
    }

    String key = makeKey(dataId, group);
    ConcurrentMap<String, CopyOnWriteArrayList<ManagerListener>> map = allListeners.get(key);
    if (map == null) {
        map = new ConcurrentHashMap<String, CopyOnWriteArrayList<ManagerListener>>();
        ConcurrentMap<String, CopyOnWriteArrayList<ManagerListener>> oldMap = allListeners.putIfAbsent(key,
                map);
        if (oldMap != null) {
            map = oldMap;
        }
    }

    CopyOnWriteArrayList<ManagerListener> listenerList = map.get(instanceId);
    if (listenerList == null) {
        listenerList = new CopyOnWriteArrayList<ManagerListener>();
        CopyOnWriteArrayList<ManagerListener> oldList = map.putIfAbsent(instanceId, listenerList);
        if (oldList != null) {
            listenerList = oldList;
        }
    }
    listenerList.addAll(addListeners);
}