Java Code Examples for java.util.concurrent.ConcurrentHashMap#get()

The following examples show how to use java.util.concurrent.ConcurrentHashMap#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SlowQueryReport.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
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;
}
 
Example 2
Source File: AlertAssociations.java    From StatsAgg with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: ConsulRegistry.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
        }
    }
}
 
Example 4
Source File: SoftRefLogWriter.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
/**
 * 创建一个记录对象, 或者返回缓存中已有的记录。
 */
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);
    }
}
 
Example 5
Source File: ConcurrentLongHashMapTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example 6
Source File: SunLayoutEngine.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 7
Source File: ChannelBufferManager.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 8
Source File: CollectionUtils.java    From litchi with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 9
Source File: IncrementalAttributeAggregatorExtensionHolder.java    From siddhi with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 10
Source File: PullAPIWrapper.java    From RocketMQ-Master-analyze with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 11
Source File: SunFontManager.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 12
Source File: ConcurrentHashMapValues.java    From caravan with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 13
Source File: StreamProcessorExtensionHolder.java    From siddhi with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 14
Source File: DelayedHashMap.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public V get(Object key) {
    for (ConcurrentHashMap<K, V> segment : segments) {
        if (segment.containsKey(key)) {
            return segment.get(key);
        }
    }
    return null;
}
 
Example 15
Source File: ConsumerOffsetManager.java    From RocketMQ-Master-analyze with Apache License 2.0 5 votes vote down vote up
/**
 * 查询偏移量
 * 
 * @param group
 * @param topic
 * @param queueId
 * @return
 */
public long queryOffset(final String group, final String topic, final int queueId) {
    // topic@group
    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;
}
 
Example 16
Source File: MetricService.java    From tutorials with MIT License 5 votes vote down vote up
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);
}
 
Example 17
Source File: RuleProvenanceFeaturizer.java    From phrasal with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 18
Source File: HTTPEndpointManager.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 19
Source File: FontUtilities.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
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;
    }
 
Example 20
Source File: KAStarNode.java    From OSPREY3 with GNU General Public License v2.0 3 votes vote down vote up
private boolean childScoreNeedsRefinement(ConcurrentHashMap<Integer, PFAbstract> lbPFs) {

		PFAbstract pf = lbPFs.get(2);

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

		if(!KSImplKAStar.useTightBounds)
			return false;

		return true;
	}