下面列出了java.util.concurrent.ConcurrentHashMap#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
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;
}
/**
* 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());
}
}
}
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);
}
}
}
/**
* 创建一个记录对象, 或者返回缓存中已有的记录。
*/
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);
}
}
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;
}
/**
* 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;
}
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;
}
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;
}
@Override
public V get(Object key) {
for (ConcurrentHashMap<K, V> segment : segments) {
if (segment.containsKey(key)) {
return segment.get(key);
}
}
return null;
}
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);
}
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);
}
}
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);
}
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);
}
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;
}
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;
}
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;
}
private boolean childScoreNeedsRefinement(ConcurrentHashMap<Integer, PFAbstract> lbPFs) {
PFAbstract pf = lbPFs.get(2);
if(!pf.isFullyDefined()) return true;
if(!KSImplKAStar.useTightBounds)
return false;
return true;
}