java.util.concurrent.ConcurrentHashMap#get ( )源码实例Demo

下面列出了java.util.concurrent.ConcurrentHashMap#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Tomcat8-Source-Read   文件: SlowQueryReport.java
protected QueryStats getQueryStats(String sql) {
    if (sql==null) sql = "";
    ConcurrentHashMap<String,QueryStats> queries = SlowQueryReport.this.queries;
    if (queries==null) {
        if (log.isWarnEnabled()) log.warn("Connection has already been closed or abandoned");
        return null;
    }
    QueryStats qs = queries.get(sql);
    if (qs == null) {
        qs = new QueryStats(sql);
        if (queries.putIfAbsent(sql,qs)!=null) {
            qs = queries.get(sql);
        } else {
            //we added a new element, see if we need to remove the oldest
            if (queries.size() > maxQueries) {
                removeOldest(queries);
            }
        }
    }
    return qs;
}
 
源代码2 项目: StatsAgg   文件: AlertAssociations.java
private static HashSet<String> getActiveAlertMetricKeys(Alert alert, ConcurrentHashMap<Integer,List<String>> alertMetricKeysByAlertId) {
    
    if ((alert == null) || (alertMetricKeysByAlertId == null)) {
        return new HashSet<>();
    }
    
    // make a local copy of the relevant 'active alerts' list
    List<String> activeAlertMetricKeys;
    HashSet<String> activeAlertMetricKeysLocal = new HashSet<>();
    synchronized(alertMetricKeysByAlertId) {
        activeAlertMetricKeys = alertMetricKeysByAlertId.get(alert.getId());
        if (activeAlertMetricKeys != null) activeAlertMetricKeysLocal = new HashSet<>(activeAlertMetricKeys);
    }
    
    // don't display metrics that have been 'forgotten', but haven't gone through the alert-routine yet
    List<String> keysToRemove = new ArrayList<>();
    for (String activeAlertMetricKey : activeAlertMetricKeysLocal) {
        if (!GlobalVariables.metricKeysLastSeenTimestamp.containsKey(activeAlertMetricKey)) keysToRemove.add(activeAlertMetricKey);
    }
    activeAlertMetricKeysLocal.removeAll(GlobalVariables.immediateCleanupMetrics.keySet());
    activeAlertMetricKeysLocal.removeAll(keysToRemove);
    
    return activeAlertMetricKeysLocal;
}
 
源代码3 项目: light-4j   文件: ConsulRegistry.java
/**
 * update service cache of the serviceName.
 * update local cache when service list changed,
 * if need notify, notify service
 *
 * @param serviceName
 * @param serviceUrls
 * @param needNotify
 */
private void updateServiceCache(String serviceName, ConcurrentHashMap<String, List<URL>> serviceUrls, boolean needNotify) {
    if (serviceUrls != null && !serviceUrls.isEmpty()) {
        List<URL> cachedUrls = serviceCache.get(serviceName);
        List<URL> newUrls = serviceUrls.get(serviceName);
        try {
            logger.trace("serviceUrls = {}", Config.getInstance().getMapper().writeValueAsString(serviceUrls));
        } catch(Exception e) {
        }
        boolean change = true;
        if (ConsulUtils.isSame(newUrls, cachedUrls)) {
            change = false;
        } else {
            serviceCache.put(serviceName, newUrls);
        }
        if (change && needNotify) {
            notifyExecutor.execute(new NotifyService(serviceName, newUrls));
            logger.info("light service notify-service: " + serviceName);
            StringBuilder sb = new StringBuilder();
            for (URL url : newUrls) {
                sb.append(url.getUri()).append(";");
            }
            logger.info("consul notify urls:" + sb.toString());
        }
    }
}
 
源代码4 项目: pulsar   文件: ConcurrentLongHashMapTest.java
public void benchConcurrentHashMap() throws Exception {
    ConcurrentHashMap<Long, String> map = new ConcurrentHashMap<Long, String>(N, 0.66f, 1);

    for (long i = 0; i < Iterations; i++) {
        for (int j = 0; j < N; j++) {
            map.put(i, "value");
        }

        for (long h = 0; h < ReadIterations; h++) {
            for (int j = 0; j < N; j++) {
                map.get(i);
            }
        }

        for (int j = 0; j < N; j++) {
            map.remove(i);
        }
    }
}
 
源代码5 项目: tddl5   文件: SoftRefLogWriter.java
/**
 * 创建一个记录对象, 或者返回缓存中已有的记录。
 */
public LogCounter getCounter(Object[] keys, Object[] fields) {
    ConcurrentHashMap<LogKey, Reference<LogCounter>> map = this.map;
    LogKey logKey = new LogKey(keys);
    LogCounter counter;
    for (;;) {
        Reference<LogCounter> entry = map.get(logKey);
        if (entry == null) {
            LogCounter newCounter = new LogCounter(logKey, (fields == null) ? keys : fields);
            entry = map.putIfAbsent(logKey, createLogRef(logKey, newCounter));
            if (entry == null) {
                expungeLogRef();
                return newCounter;
            }
        }
        counter = entry.get();
        if (counter != null) {
            return counter;
        }
        map.remove(logKey);
    }
}
 
源代码6 项目: AIDR   文件: ChannelBufferManager.java
private int deleteMapRecordsForCollection(final String deleteCollectionCode, ConcurrentHashMap<CounterKey, Object> dataMap) {
	int count = 0;
	Iterator<CounterKey> itr = dataMap.keySet().iterator();
	while (itr.hasNext()) {
		CounterKey keyVal = itr.next();
		MapRecord data = (MapRecord) dataMap.get(keyVal);
		if (keyVal.getCrisisCode().equals(deleteCollectionCode) && data != null && data.isCountZeroForAllGranularity()) {
			synchronized (dataMap) {		// prevent modification while deletion attempt
				dataMap.remove(keyVal);
				++count;
			}
		}
	}
	return count;
}
 
源代码7 项目: micro-integrator   文件: HTTPEndpointManager.java
/**
 * Method for get WorkerPool Config
 *
 * @param tenantDomain
 * @param port
 * @return
 */
public WorkerPoolConfiguration getWorkerPoolConfiguration(String tenantDomain, int port) {
    ConcurrentHashMap concurrentHashMap = workerPoolMap.get(tenantDomain);
    if (concurrentHashMap != null) {
        Object val = concurrentHashMap.get(port);
        if (val instanceof WorkerPoolConfiguration) {
            return (WorkerPoolConfiguration) val;
        }
    }
    return null;
}
 
源代码8 项目: phrasal   文件: RuleProvenanceFeaturizer.java
private String getFeatureName(String phraseTableName, ConcurrentHashMap<String, String> map, String featureLabel) {
  String result = map.get(phraseTableName);
  if(result != null) return result;
  
  result = featureLabel + ":" + phraseTableName;
  map.put(phraseTableName, result);
  return result;
}
 
源代码9 项目: tutorials   文件: MetricService.java
private void increaseMainMetric(final String request, final int status) {
    ConcurrentHashMap<Integer, Integer> statusMap = metricMap.get(request);
    if (statusMap == null) {
        statusMap = new ConcurrentHashMap<Integer, Integer>();
    }

    Integer count = statusMap.get(status);
    if (count == null) {
        count = 1;
    } else {
        count++;
    }
    statusMap.put(status, count);
    metricMap.put(request, statusMap);
}
 
/**
 * 查询偏移量
 * 
 * @param group
 * @param topic
 * @param queueId
 * @return
 */
public long queryOffset(final String group, final String topic, final int queueId) {
    // [email protected]
    String key = topic + TOPIC_GROUP_SEPARATOR + group;
    ConcurrentHashMap<Integer, Long> map = this.offsetTable.get(key);
    if (null != map) {
        Long offset = map.get(queueId);
        if (offset != null)
            return offset;
    }

    return -1;
}
 
源代码11 项目: jstarcraft-core   文件: DelayedHashMap.java
@Override
public V get(Object key) {
    for (ConcurrentHashMap<K, V> segment : segments) {
        if (segment.containsKey(key)) {
            return segment.get(key);
        }
    }
    return null;
}
 
源代码12 项目: siddhi   文件: StreamProcessorExtensionHolder.java
public static StreamProcessorExtensionHolder getInstance(SiddhiAppContext siddhiAppContext) {
    ConcurrentHashMap<Class, AbstractExtensionHolder> extensionHolderMap = siddhiAppContext.getSiddhiContext
            ().getExtensionHolderMap();
    AbstractExtensionHolder abstractExtensionHolder = extensionHolderMap.get(clazz);
    if (abstractExtensionHolder == null) {
        abstractExtensionHolder = new StreamProcessorExtensionHolder(siddhiAppContext);
        extensionHolderMap.putIfAbsent(clazz, abstractExtensionHolder);
    }
    return (StreamProcessorExtensionHolder) extensionHolderMap.get(clazz);
}
 
源代码13 项目: caravan   文件: ConcurrentHashMapValues.java
public static <K, V> V getOrAddWithLock(ConcurrentHashMap<K, V> map, K key, Func<V> valueCreator) {
    checkArgument(map, key, valueCreator);

    V value = map.get(key);
    if (value != null)
        return value;

    synchronized (map) {
        return internalGetOrAdd(map, key, valueCreator);
    }
}
 
源代码14 项目: openjdk-jdk8u-backup   文件: SunFontManager.java
protected static void registerCompositeFont(String compositeName,
                                            String[] componentFileNames,
                                            String[] componentNames,
                                            int numMetricsSlots,
                                            int[] exclusionRanges,
                                            int[] exclusionMaxIndex,
                                            boolean defer,
                                            ConcurrentHashMap<String, Font2D>
                                            altNameCache) {

    CompositeFont cf = new CompositeFont(compositeName,
                                         componentFileNames,
                                         componentNames,
                                         numMetricsSlots,
                                         exclusionRanges,
                                         exclusionMaxIndex, defer,
                                         SunFontManager.getInstance());

    /* if the cache has an existing composite for this case, make
     * its handle point to this new font.
     * This ensures that when the altNameCache that is passed in
     * is the global mapNameCache - ie we are running as an application -
     * that any statically created java.awt.Font instances which already
     * have a Font2D instance will have that re-directed to the new Font
     * on subsequent uses. This is particularly important for "the"
     * default font instance, or similar cases where a UI toolkit (eg
     * Swing) has cached a java.awt.Font. Note that if Swing is using
     * a custom composite APIs which update the standard composites have
     * no effect - this is typically the case only when using the Windows
     * L&F where these APIs would conflict with that L&F anyway.
     */
    Font2D oldFont = (Font2D)
        altNameCache.get(compositeName.toLowerCase(Locale.ENGLISH));
    if (oldFont instanceof CompositeFont) {
        oldFont.handle.font2D = cf;
    }
    altNameCache.put(compositeName.toLowerCase(Locale.ENGLISH), cf);
}
 
源代码15 项目: RocketMQ-Master-analyze   文件: PullAPIWrapper.java
private String computPullFromWhichFilterServer(final String topic, final String brokerAddr)
        throws MQClientException {
    ConcurrentHashMap<String, TopicRouteData> topicRouteTable = this.mQClientFactory.getTopicRouteTable();
    if (topicRouteTable != null) {
        TopicRouteData topicRouteData = topicRouteTable.get(topic);
        List<String> list = topicRouteData.getFilterServerTable().get(brokerAddr);

        if (list != null && !list.isEmpty()) {
            return list.get(randomNum() % list.size());
        }
    }

    throw new MQClientException(
        "Find Filter Server Failed, Broker Addr: " + brokerAddr + " topic: " + topic, null);
}
 
public static IncrementalAttributeAggregatorExtensionHolder getInstance(SiddhiAppContext siddhiAppContext) {
    ConcurrentHashMap<Class, AbstractExtensionHolder> extensionHolderMap = siddhiAppContext.getSiddhiContext()
            .getExtensionHolderMap();
    AbstractExtensionHolder abstractExtensionHolder = extensionHolderMap.get(clazz);
    if (abstractExtensionHolder == null) {
        abstractExtensionHolder = new IncrementalAttributeAggregatorExtensionHolder(siddhiAppContext);
        extensionHolderMap.putIfAbsent(clazz, abstractExtensionHolder);
    }
    return (IncrementalAttributeAggregatorExtensionHolder) extensionHolderMap.get(clazz);
}
 
源代码17 项目: litchi   文件: CollectionUtils.java
public static Page valueOf(int page, int segment) {
	ConcurrentHashMap<Integer, Page> pages = cache.get(segment);
	if (pages == null) {
		pages = new ConcurrentHashMap<>();
		cache.put(segment, pages);
	}
	Page p = pages.get(page);
	if (p == null) {
		int start = (page - 1) * segment + 1;
		long end = page * segment;
		p = new Page(page, start, end);
		pages.put(page, p);
	}
	return p;
}
 
源代码18 项目: Bytecoder   文件: SunLayoutEngine.java
public LayoutEngine getEngine(LayoutEngineKey key) {
    ConcurrentHashMap<LayoutEngineKey, LayoutEngine> cache = cacheref.get();
    if (cache == null) {
        cache = new ConcurrentHashMap<>();
        cacheref = new SoftReference<>(cache);
    }

    LayoutEngine e = cache.get(key);
    if (e == null) {
        LayoutEngineKey copy = key.copy();
        e = new SunLayoutEngine(copy);
        cache.put(copy, e);
    }
    return e;
}
 
源代码19 项目: Bytecoder   文件: FontUtilities.java
public static FontUIResource getCompositeFontUIResource(Font font) {

        FontUIResource fuir = new FontUIResource(font);
        Font2D font2D = FontUtilities.getFont2D(font);

        if (!(font2D instanceof PhysicalFont)) {
            /* Swing should only be calling this when a font is obtained
             * from desktop properties, so should generally be a physical font,
             * an exception might be for names like "MS Serif" which are
             * automatically mapped to "Serif", so there's no need to do
             * anything special in that case. But note that suggested usage
             * is first to call fontSupportsDefaultEncoding(Font) and this
             * method should not be called if that were to return true.
             */
             return fuir;
        }

        FontManager fm = FontManagerFactory.getInstance();
        Font2D dialog = fm.findFont2D("dialog", font.getStyle(), FontManager.NO_FALLBACK);
        // Should never be null, but MACOSX fonts are not CompositeFonts
        if (dialog == null || !(dialog instanceof CompositeFont)) {
            return fuir;
        }
        CompositeFont dialog2D = (CompositeFont)dialog;
        PhysicalFont physicalFont = (PhysicalFont)font2D;
        ConcurrentHashMap<PhysicalFont, CompositeFont> compMap = compMapRef.get();
        if (compMap == null) { // Its been collected.
            compMap = new ConcurrentHashMap<PhysicalFont, CompositeFont>();
            compMapRef = new SoftReference<>(compMap);
        }
        CompositeFont compFont = compMap.get(physicalFont);
        if (compFont == null) {
            compFont = new CompositeFont(physicalFont, dialog2D);
            compMap.put(physicalFont, compFont);
        }
        FontAccess.getFontAccess().setFont2D(fuir, compFont.handle);
        /* marking this as a created font is needed as only created fonts
         * copy their creator's handles.
         */
        FontAccess.getFontAccess().setCreatedFont(fuir);
        return fuir;
    }
 
源代码20 项目: OSPREY3   文件: KAStarNode.java
private boolean childScoreNeedsRefinement(ConcurrentHashMap<Integer, PFAbstract> lbPFs) {

		PFAbstract pf = lbPFs.get(2);

		if(!pf.isFullyDefined()) return true;

		if(!KSImplKAStar.useTightBounds)
			return false;

		return true;
	}