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.archive.crawler.admin.StatisticsTracker.java

/**
 * Increment a counter for a key in a given HashMap by an arbitrary amount.
 * Used for various aggregate data. The increment amount can be negative.
 *
 * @param map//w  w  w . ja va2s .  c o  m
 *            The Map or ConcurrentMap
 * @param key
 *            The key for the counter to be incremented, if it does not exist
 *            it will be added (set to equal to <code>increment</code>).
 *            If null it will increment the counter "unknown".
 * @param increment
 *            The amount to increment counter related to the <code>key</code>.
 */
protected static void incrementMapCount(ConcurrentMap<String, AtomicLong> map, String key, long increment) {
    if (key == null) {
        key = "unknown";
    }
    AtomicLong lw = map.get(key);
    if (lw == null) {
        lw = new AtomicLong();
        AtomicLong prevVal = map.putIfAbsent(key, lw);
        if (prevVal != null) {
            lw = prevVal;
        }
    }
    lw.addAndGet(increment);
}

From source file:xbird.xquery.dm.instance.DocumentTableModel.java

private static synchronized void setPool(MemoryMappedDocumentTable mmDoctbl, String docId) throws IOException {
    ConcurrentMap<String, MemoryMappedDocumentTable> cache = _remoteDoctblCache;
    if (cache == null) {
        cache = new ConcurrentReferenceHashMap<String, MemoryMappedDocumentTable>(16, ReferenceType.STRONG,
                ReferenceType.SOFT);
        _remoteDoctblCache = cache;/*  ww w .ja v a2s. co  m*/
    }
    MemoryMappedDocumentTable prevDoctbl = cache.putIfAbsent(docId, mmDoctbl);
    if (prevDoctbl != null) {
        ILongCache<int[]> prevCache = prevDoctbl.getBufferPool();
        if (prevCache != null) {
            mmDoctbl.setBufferPool(prevCache);
        }
    } else {
        File tmpDir = (TMP_DATA_DIR == null) ? null : new File(TMP_DATA_DIR);
        String docname = FileUtils.basename(docId);
        File tmpFile = File.createTempFile(docname, ".tmp", tmpDir);
        tmpFile.deleteOnExit();
        ILongCache<int[]> pool = new DiskPagedLongCache<int[]>(tmpFile, MemoryMappedDocumentTable.CACHED_PAGES,
                new IntCodec());
        mmDoctbl.setBufferPool(pool);
    }
}

From source file:com.buddycloud.mediaserver.web.MediaServerResource.java

@SuppressWarnings("unchecked")
protected 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;/* w w  w .j av  a 2s  .  c o  m*/
        }
    }

    return headers;
}

From source file:com.weibo.api.motan.util.StatsUtil.java

public static void logAccessStatistic(boolean clear) {
    DecimalFormat mbFormat = new DecimalFormat("#0.00");
    long currentTimeMillis = System.currentTimeMillis();

    ConcurrentMap<String, AccessStatisticResult> totalResults = new ConcurrentHashMap<String, AccessStatisticResult>();

    for (Map.Entry<String, AccessStatisticItem> entry : accessStatistics.entrySet()) {
        AccessStatisticItem item = entry.getValue();

        AccessStatisticResult result = item.getStatisticResult(currentTimeMillis,
                MotanConstants.STATISTIC_PEROID);

        if (clear) {
            item.clearStatistic(currentTimeMillis, MotanConstants.STATISTIC_PEROID);
        }//w w w.  j  a va 2s  .  c o  m

        String key = entry.getKey();
        String[] keys = key.split(SEPARATE);
        if (keys.length != 3) {
            continue;
        }
        String application = keys[1];
        String module = keys[2];
        key = application + "|" + module;
        AccessStatisticResult appResult = totalResults.get(key);
        if (appResult == null) {
            totalResults.putIfAbsent(key, new AccessStatisticResult());
            appResult = totalResults.get(key);
        }

        appResult.totalCount += result.totalCount;
        appResult.bizExceptionCount += result.bizExceptionCount;
        appResult.slowCount += result.slowCount;
        appResult.costTime += result.costTime;
        appResult.bizTime += result.bizTime;
        appResult.otherExceptionCount += result.otherExceptionCount;

        Snapshot snapshot = InternalMetricsFactory.getRegistryInstance(entry.getKey()).histogram(HISTOGRAM_NAME)
                .getSnapshot();

        if (application.equals(APPLICATION_STATISTIC)) {
            continue;
        }
        if (result.totalCount == 0) {
            LoggerUtil.accessStatsLog("[motan-accessStatistic] app: " + application + " module: " + module
                    + " item: " + keys[0]
                    + " total_count: 0 slow_count: 0 biz_excp: 0 other_excp: 0 avg_time: 0.00ms biz_time: 0.00ms avg_tps: 0 max_tps: 0 min_tps: 0");
        } else {
            LoggerUtil.accessStatsLog(
                    "[motan-accessStatistic] app: {} module: {} item: {} total_count: {} slow_count: {} p75: {} p95: {} p98: {} p99: {} p999: {} biz_excp: {} other_excp: {} avg_time: {}ms biz_time: {}ms avg_tps: {} max_tps: {} min_tps: {} ",
                    application, module, keys[0], result.totalCount, result.slowCount,
                    mbFormat.format(snapshot.get75thPercentile()),
                    mbFormat.format(snapshot.get95thPercentile()),
                    mbFormat.format(snapshot.get98thPercentile()),
                    mbFormat.format(snapshot.get99thPercentile()),
                    mbFormat.format(snapshot.get999thPercentile()), result.bizExceptionCount,
                    result.otherExceptionCount, mbFormat.format(result.costTime / result.totalCount),
                    mbFormat.format(result.bizTime / result.totalCount),
                    (result.totalCount / MotanConstants.STATISTIC_PEROID), result.maxCount, result.minCount);
        }

    }

    if (!totalResults.isEmpty()) {
        for (Map.Entry<String, AccessStatisticResult> entry : totalResults.entrySet()) {
            String application = entry.getKey().split(SEPARATE)[0];
            String module = entry.getKey().split(SEPARATE)[1];
            AccessStatisticResult totalResult = entry.getValue();
            Snapshot snapshot = InternalMetricsFactory.getRegistryInstance(entry.getKey())
                    .histogram(HISTOGRAM_NAME).getSnapshot();
            if (totalResult.totalCount > 0) {
                LoggerUtil.accessStatsLog(
                        "[motan-totalAccessStatistic] app: {} module: {} total_count: {} slow_count: {} p75: {} p95: {} p98: {} p99: {} p999: {} biz_excp: {} other_excp: {} avg_time: {}ms biz_time: {}ms avg_tps: {}",
                        application, module, totalResult.totalCount, totalResult.slowCount,
                        mbFormat.format(snapshot.get75thPercentile()),
                        mbFormat.format(snapshot.get95thPercentile()),
                        mbFormat.format(snapshot.get98thPercentile()),
                        mbFormat.format(snapshot.get99thPercentile()),
                        mbFormat.format(snapshot.get999thPercentile()), totalResult.bizExceptionCount,
                        totalResult.otherExceptionCount,
                        mbFormat.format(totalResult.costTime / totalResult.totalCount),
                        mbFormat.format(totalResult.bizTime / totalResult.totalCount),
                        (totalResult.totalCount / MotanConstants.STATISTIC_PEROID));
            } else {
                LoggerUtil.accessStatsLog("[motan-totalAccessStatistic] app: " + application + " module: "
                        + module
                        + " total_count: 0 slow_count: 0 biz_excp: 0 other_excp: 0 avg_time: 0.00ms biz_time: 0.00ms avg_tps: 0");
            }

        }
    } else {
        LoggerUtil.accessStatsLog("[motan-totalAccessStatistic] app: " + URLParamType.application.getValue()
                + " module: " + URLParamType.module.getValue()
                + " total_count: 0 slow_count: 0 biz_excp: 0 other_excp: 0 avg_time: 0.00ms biz_time: 0.00ms avg_tps: 0");
    }

}

From source file:org.apache.hadoop.hbase.regionserver.wal.SequenceIdAccounting.java

/**
 * We've been passed a new sequenceid for the region. Set it as highest seen for this region and
 * if we are to record oldest, or lowest sequenceids, save it as oldest seen if nothing
 * currently older.//w  w  w  .ja  v  a2s  .  c om
 * @param encodedRegionName
 * @param families
 * @param sequenceid
 * @param lowest Whether to keep running account of oldest sequence id.
 */
void update(byte[] encodedRegionName, Set<byte[]> families, long sequenceid, final boolean lowest) {
    Long l = Long.valueOf(sequenceid);
    this.highestSequenceIds.put(encodedRegionName, l);
    if (lowest) {
        ConcurrentMap<byte[], Long> m = getOrCreateLowestSequenceIds(encodedRegionName);
        for (byte[] familyName : families) {
            m.putIfAbsent(familyName, l);
        }
    }
}

From source file:org.apache.hadoop.hbase.client.MetaCache.java

/**
 * Put a newly discovered HRegionLocation into the cache.
 * @param tableName The table name./*  w w  w . ja  v  a 2s .c  o  m*/
 * @param locations the new locations
 */
public void cacheLocation(final TableName tableName, final RegionLocations locations) {
    byte[] startKey = locations.getRegionLocation().getRegionInfo().getStartKey();
    ConcurrentMap<byte[], RegionLocations> tableLocations = getTableLocations(tableName);
    RegionLocations oldLocation = tableLocations.putIfAbsent(startKey, locations);
    boolean isNewCacheEntry = (oldLocation == null);
    if (isNewCacheEntry) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Cached location: " + locations);
        }
        addToCachedServers(locations);
        return;
    }

    // merge old and new locations and add it to the cache
    // Meta record might be stale - some (probably the same) server has closed the region
    // with later seqNum and told us about the new location.
    RegionLocations mergedLocation = oldLocation.mergeLocations(locations);
    boolean replaced = tableLocations.replace(startKey, oldLocation, mergedLocation);
    if (replaced && LOG.isTraceEnabled()) {
        LOG.trace("Merged cached locations: " + mergedLocation);
    }
    addToCachedServers(locations);
}

From source file:org.slc.sli.ingestion.aspect.StageTrackingAspect.java

private void trackCallStatistics(String statsKey, long elapsed) {
    String jobId = TenantContext.getJobId();
    if (jobId != null) {

        ConcurrentMap<String, Pair<AtomicLong, AtomicLong>> statsForJob = stats.get(jobId);
        if (statsForJob == null) {
            stats.putIfAbsent(jobId, new ConcurrentHashMap<String, Pair<AtomicLong, AtomicLong>>());
            statsForJob = stats.get(jobId);
        }//  www  .  j a va 2  s  . co  m

        Pair<AtomicLong, AtomicLong> pair = statsForJob.get(statsKey);
        if (pair == null) {
            statsForJob.putIfAbsent(statsKey, Pair.of(new AtomicLong(0L), new AtomicLong(0L)));
            pair = statsForJob.get(statsKey);
        }

        // increment
        pair.getLeft().incrementAndGet();
        pair.getRight().addAndGet(elapsed);
    }
}

From source file:com.enonic.vertical.userservices.UserServicesAccessManagerImpl.java

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

    String allowRules = sitePropertiesService.getProperty(HTTP_SERVICES_ALLOW_PROPERTY, site);
    String denyRules = sitePropertiesService.getProperty(HTTP_SERVICES_DENY_PROPERTY, site);
    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.onosproject.store.trivial.impl.SimpleFlowRuleStore.java

private List<StoredFlowEntry> getFlowEntries(DeviceId deviceId, FlowId flowId) {
    final ConcurrentMap<FlowId, List<StoredFlowEntry>> flowTable = getFlowTable(deviceId);
    List<StoredFlowEntry> r = flowTable.get(flowId);
    if (r == null) {
        final List<StoredFlowEntry> concurrentlyAdded;
        r = new CopyOnWriteArrayList<>();
        concurrentlyAdded = flowTable.putIfAbsent(flowId, r);
        if (concurrentlyAdded != null) {
            return concurrentlyAdded;
        }/*from   w w  w  . ja  v a2 s  .  co m*/
    }
    return r;
}

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

private AccessPermission applyAccessRules(String service, String operation,
        ConcurrentMap<String, AccessPermission> siteRules) {
    // search for specific rule: "service.operation"
    AccessPermission accessServiceOperation = siteRules.get(service + "." + operation);
    if (accessServiceOperation != null) {
        return accessServiceOperation;
    }//  w  ww  . j av a2  s.  com

    // search for generic rule: "service.*"
    AccessPermission accessService = siteRules.get(service + ".*");
    if (accessService != null) {
        siteRules.putIfAbsent(service + "." + operation, accessService);
        return accessService;
    }

    // no rule found -> return default and cache value
    AccessPermission defaultAccess = siteRules.get(ACCESS_RULE_ALL);
    siteRules.putIfAbsent(service + "." + operation, defaultAccess);
    return defaultAccess;
}