下面列出了java.util.concurrent.ConcurrentHashMap#containsKey ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public boolean cacheStatement(CachedStatement proxy) {
ConcurrentHashMap<CacheKey,CachedStatement> cache = getCache();
if (cache == null) return false;
if (proxy.getCacheKey()==null) {
return false;
} else if (cache.containsKey(proxy.getCacheKey())) {
return false;
} else if (cacheSize.get()>=maxCacheSize) {
return false;
} else if (cacheSize.incrementAndGet()>maxCacheSize) {
cacheSize.decrementAndGet();
return false;
} else {
//cache the statement
cache.put(proxy.getCacheKey(), proxy);
return true;
}
}
/**
* 获取服务提供者的某个属性的初始化值
*
* @author sxp
* @since 2018/8/11
*/
public static Object getInitProperty(String serviceName, String ip, int port, String propertyKey) {
if (!serviceProvidersConfig.containsKey(serviceName)) {
return null;
}
ConcurrentHashMap<String, BasicProvider> providersConfig = serviceProvidersConfig.get(serviceName);
String key = ip + ":" + port;
if (!providersConfig.containsKey(key)) {
return null;
}
BasicProvider provider = providersConfig.get(key);
ConcurrentHashMap<String, Object> initProperties = provider.getInitProperties();
return initProperties.get(propertyKey);
}
/**
* Update value in hosted apps cache
* @param hostname Host name
* @param appId Application Id
*/
public void putIfModifiedHostedAppsMetadata(String hostname, String appId) {
TimelineMetricHostMetadata timelineMetricHostMetadata = HOSTED_APPS_MAP.get(hostname);
ConcurrentHashMap<String, String> apps = (timelineMetricHostMetadata != null) ? timelineMetricHostMetadata.getHostedApps() : null;
if (apps == null) {
apps = new ConcurrentHashMap<>();
if (timelineMetricHostMetadata == null) {
TimelineMetricHostMetadata newHostMetadata = new TimelineMetricHostMetadata(apps);
HOSTED_APPS_MAP.put(hostname, newHostMetadata);
} else {
HOSTED_APPS_MAP.get(hostname).setHostedApps(apps);
}
}
if (!apps.containsKey(appId)) {
apps.put(appId, appId);
SYNC_HOSTED_APPS_METADATA.set(true);
}
}
public static void register(EventBus bus, Object target) {
ConcurrentHashMap<Object, ArrayList<IEventListener>> listeners = ReflectionHelper.getPrivateValue(EventBus.class, bus, "listeners");
Map<Object, ModContainer> listenerOwners = ReflectionHelper.getPrivateValue(EventBus.class, bus, "listenerOwners");
if (listeners.containsKey(target)) {
return;
}
ModContainer activeModContainer = Loader.instance().getMinecraftModContainer();
listenerOwners.put(target, activeModContainer);
ReflectionHelper.setPrivateValue(EventBus.class, bus, listenerOwners, "listenerOwners");
Set<? extends Class<?>> supers = TypeToken.of(target.getClass()).getTypes().rawTypes();
for (Method method : target.getClass().getMethods()) {
for (Class<?> cls : supers) {
try {
Method real = cls.getDeclaredMethod(method.getName(), method.getParameterTypes());
if (real.isAnnotationPresent(SubscribeEvent.class)) {
Class<?>[] parameterTypes = method.getParameterTypes();
Class<?> eventType = parameterTypes[0];
register(bus, eventType, target, method, activeModContainer);
break;
}
} catch (NoSuchMethodException ignored) {
}
}
}
}
public boolean cacheStatement(CachedStatement proxy) {
@SuppressWarnings("unchecked")
ConcurrentHashMap<CacheKey,CachedStatement> cache =
(ConcurrentHashMap<CacheKey,CachedStatement>)pcon.getAttributes().get(STATEMENT_CACHE_ATTR);
if (proxy.getCacheKey()==null) {
return false;
} else if (cache.containsKey(proxy.getCacheKey())) {
return false;
} else if (cacheSize.get()>=maxCacheSize) {
return false;
} else if (cacheSize.incrementAndGet()>maxCacheSize) {
cacheSize.decrementAndGet();
return false;
} else {
//cache the statement
cache.put(proxy.getCacheKey(), proxy);
return true;
}
}
@Override
public void run() {
// run the association routine against all metric-groups/metric-suspensions/metric-keys. should only run the pattern matcher against previously unknown metric-keys.
for (String metricKey : metricKeys__) {
ConcurrentHashMap<String,String> immediateCleanupMetrics = GlobalVariables.immediateCleanupMetrics;
if ((immediateCleanupMetrics != null) && !immediateCleanupMetrics.isEmpty() && immediateCleanupMetrics.containsKey(metricKey)) continue;
associateMetricKeyWithIds(metricKey, allMetricGroupIds__,
GlobalVariables.matchingMetricKeysAssociatedWithMetricGroup, GlobalVariables.metricKeysAssociatedWithAnyMetricGroup,
GlobalVariables.mergedMatchRegexesByMetricGroupId, GlobalVariables.mergedBlacklistRegexesByMetricGroupId);
associateMetricKeyWithIds(metricKey, allMetricSuspensionIds__,
GlobalVariables.matchingMetricKeysAssociatedWithSuspension, GlobalVariables.metricKeysAssociatedWithAnySuspension,
GlobalVariables.mergedMatchRegexesBySuspensionId, GlobalVariables.mergedBlacklistRegexesBySuspensionId);
}
}
/**
* 检查方法,例如方法名、多态(重载)方法
*
* @param itfClass 接口类
*/
protected void checkMethods(Class<?> itfClass) {
ConcurrentHashMap<String, Boolean> methodsLimit = new ConcurrentHashMap<String, Boolean>();
for (Method method : itfClass.getMethods()) {
String methodName = method.getName();
if (methodsLimit.containsKey(methodName)) {
// 重名的方法
if (LOGGER.isWarnEnabled(providerConfig.getAppName())) {
// TODO WARN
LOGGER.warnWithApp(providerConfig.getAppName(), "Method with same name \"" + itfClass.getName()
+ "." + methodName + "\" exists ! The usage of overloading method in rpc is deprecated.");
}
}
// 判断服务下方法的黑白名单
Boolean include = methodsLimit.get(methodName);
if (include == null) {
include = inList(providerConfig.getInclude(), providerConfig.getExclude(), methodName); // 检查是否在黑白名单中
methodsLimit.putIfAbsent(methodName, include);
}
}
providerConfig.setMethodsLimit(methodsLimit);
}
/**
* Remove Worker Pool
*
* @param tenantDomian Tenant Domain
* @param port Port
*/
public void removeWorkerPoolConfiguration(String tenantDomian, int port) {
ConcurrentHashMap concurrentHashMap = workerPoolMap.get(tenantDomian);
if (concurrentHashMap != null) {
if (concurrentHashMap.containsKey(port)) {
concurrentHashMap.remove(port);
}
}
}
/**
* 将指定服务的参数列表值设置为字符串"null"
*
* @author sxp
* @since 2018/10/19
*/
public static void resetArgument(String serviceName) {
if (StringUtils.isEmpty(serviceName)) {
return;
}
ConcurrentHashMap<String, Object> args = arguments.get();
if (args.containsKey(serviceName)) {
args.put(serviceName, NULL_VALUE);// ConcurrentHashMap的key和value至不能为null
}
if (args.size() >= RECYCLE_NULL_VALUE_THRESHOLD) {
recycleNullValue();
}
}
public static List<ConsumerClusters> selectByTopic(String topic) {
List<ConsumerClusters> clusters = new ArrayList<ConsumerClusters>();
for (int i = 0; i < relationArray.size(); i++) {
ConcurrentHashMap<String, SubscriptionData> subscriptionTable = relationArray.get(i).getClusters().getSubMap();
if (subscriptionTable.containsKey(topic)) {
clusters.add(relationArray.get(i).getClusters());
}
}
return clusters;
}
public boolean containDataId(String dataId, String group) {
if (null == group) {
group = Constants.DEFAULT_GROUP;
}
ConcurrentHashMap<String, CacheData> cacheDatas = this.cache.get(dataId);
if (null == cacheDatas) {
return false;
}
return cacheDatas.containsKey(group);
}
public boolean containDataId(String dataId, String group) {
if (null == group) {
group = Constants.DEFAULT_GROUP;
}
ConcurrentHashMap<String, CacheData> cacheDatas = this.cache.get(dataId);
if (null == cacheDatas) {
return false;
}
return cacheDatas.containsKey(group);
}
@Override
public CloseableIteration<RyaIRI, RyaDAOException> join(C conf, Map.Entry<RyaIRI, RyaType>... predObjs) throws RyaDAOException {
ConcurrentHashMap<RyaIRI, Integer> ht = new ConcurrentHashMap<RyaIRI, Integer>();
int count = 0;
boolean first = true;
for (Map.Entry<RyaIRI, RyaType> predObj : predObjs) {
count++;
RyaIRI pred = predObj.getKey();
RyaType obj = predObj.getValue();
//query
CloseableIteration<RyaStatement, RyaDAOException> results = ryaQueryEngine.query(new RyaStatement(null, pred, obj), null);
//add to hashtable
while (results.hasNext()) {
RyaIRI subject = results.next().getSubject();
if (!first) {
if (!ht.containsKey(subject)) {
continue; //not in join
}
}
ht.put(subject, count);
}
//remove from hashtable values that are under count
if (first) {
first = false;
} else {
for (Map.Entry<RyaIRI, Integer> entry : ht.entrySet()) {
if (entry.getValue() < count) {
ht.remove(entry.getKey());
}
}
}
}
return new EnumerationWrapper<RyaIRI, RyaDAOException>(ht.keys());
}
/**
* containsKey(null) throws NPE
*/
public void testContainsKey_NullPointerException() {
ConcurrentHashMap c = new ConcurrentHashMap(5);
try {
c.containsKey(null);
shouldThrow();
} catch (NullPointerException success) {}
}
@Override
public int getInFlightRequestCount(String clusterId) {
int inFlightRequestCount = 0;
ConcurrentHashMap<String, LoadBalancerInfo> clusterIdToLoadBalancerMap = AWSLoadBalancer
.getClusterIdToLoadBalancerMap();
// Check if load balancer info is available for this cluster.
// If yes, then find difference between total requests made to the load balancer and
// total responses generated by instances attached to it.
if (clusterIdToLoadBalancerMap.containsKey(clusterId)) {
LoadBalancerInfo loadBalancerInfo = clusterIdToLoadBalancerMap
.get(clusterId);
String loadBalancerName = loadBalancerInfo.getName();
String region = loadBalancerInfo.getRegion();
// In flight request count = total requests - total responses
inFlightRequestCount = awsHelper.getRequestCount(loadBalancerName,
region, awsHelper.getStatisticsInterval())
- awsHelper.getAllResponsesCount(loadBalancerName, region,
awsHelper.getStatisticsInterval());
if (inFlightRequestCount < 0)
inFlightRequestCount = 0;
}
return inFlightRequestCount;
}
@Override
public V remove(Object key) {
for (ConcurrentHashMap<K, V> segment : segments) {
if (segment.containsKey(key)) {
return segment.remove(key);
}
}
return null;
}
public TreeMap<Calendar, Integer> getTripCountForDates() {
ConcurrentHashMap<AgencyAndId, AtomicInteger> tripsPerServHash = getTripCountsForAllServiceIDs();
TreeMap<Calendar, Integer> tripsPerDateHash = new TreeMap<Calendar, Integer>();
start.setTime(from.getAsDate(tz));
end.setTime(to.getAsDate(tz));
if (start == null){
throw new IllegalArgumentException("Calendar Date Range Improperly Set");
}
while(!start.after(end)){
Integer tripCount =0;
ServiceDate targetDay = new ServiceDate(start);
Calendar targetDayAsCal = targetDay.getAsCalendar(tz);
for (AgencyAndId sid : calendarService.getServiceIdsOnDate(targetDay)){
//System.out.println(targetDay.getAsCalendar(tz).getTime().toString() + " " +sid.toString());
if (tripsPerDateHash.containsKey(targetDayAsCal)){
tripCount = tripsPerDateHash.get(targetDayAsCal);
}
if (tripsPerServHash.containsKey(sid)){
tripCount = tripCount + tripsPerServHash.get(sid).get();
}
}
// System.out.println(targetDay.getAsCalendar(tz).getTime().toString() + " " + tripCount);
tripsPerDateHash.put(targetDay.getAsCalendar(tz), tripCount);
start.add(Calendar.DATE, 1);
}
return tripsPerDateHash;
}
public static ByteBuffer handle_dns_packet(Packet packet) {
if (DOMAINS_IP_MAPS4 == null) {
LogUtils.d(TAG, "DOMAINS_IP_MAPS IS NULL HOST FILE ERROR");
return null;
}
try {
ByteBuffer packet_buffer = packet.backingBuffer;
packet_buffer.mark();
byte[] tmp_bytes = new byte[packet_buffer.remaining()];
packet_buffer.get(tmp_bytes);
packet_buffer.reset();
Message message = new Message(tmp_bytes);
Record question = message.getQuestion();
ConcurrentHashMap<String, String> DOMAINS_IP_MAPS;
int type = question.getType();
if (type == Type.A)
DOMAINS_IP_MAPS = DOMAINS_IP_MAPS4;
else if (type == Type.AAAA)
DOMAINS_IP_MAPS = DOMAINS_IP_MAPS6;
else return null;
Name query_domain = message.getQuestion().getName();
String query_string = query_domain.toString();
LogUtils.d(TAG, "query: " + question.getType() + " :" + query_string);
if (!DOMAINS_IP_MAPS.containsKey(query_string)) {
query_string = "." + query_string;
int j = 0;
while (true) {
int i = query_string.indexOf(".", j);
if (i == -1) {
return null;
}
String str = query_string.substring(i);
if (".".equals(str) || "".equals(str)) {
return null;
}
if (DOMAINS_IP_MAPS.containsKey(str)) {
query_string = str;
break;
}
j = i + 1;
}
}
InetAddress address = Address.getByAddress(DOMAINS_IP_MAPS.get(query_string));
Record record;
if (type == Type.A) record = new ARecord(query_domain, 1, 86400, address);
else record = new AAAARecord(query_domain, 1, 86400, address);
message.addRecord(record, 1);
message.getHeader().setFlag(Flags.QR);
packet_buffer.limit(packet_buffer.capacity());
packet_buffer.put(message.toWire());
packet_buffer.limit(packet_buffer.position());
packet_buffer.reset();
packet.swapSourceAndDestination();
packet.updateUDPBuffer(packet_buffer, packet_buffer.remaining());
packet_buffer.position(packet_buffer.limit());
LogUtils.d(TAG, "hit: " + question.getType() + " :" + query_domain.toString() + " :" + address.getHostName());
return packet_buffer;
} catch (Exception e) {
LogUtils.d(TAG, "dns hook error", e);
return null;
}
}
/**
* Iterates through elements skipping white-listed patterns;
* calculates average value for each slice of each metric (last slice values could be ignored in there is the possibility that values from this slice could be present in next post);
* updates/adds the value in the cache;
* calculates applications host metrics based on the metadata of hosted apps
* updates metadata of hosted apps if needed
* @param elements
*/
@Override
public void putMetrics(Collection<TimelineMetric> elements) {
Map<String, TimelineMetricHostMetadata> hostMetadata = metricMetadataManager.getHostedAppsCache();
for (TimelineMetric metric : elements) {
if (shouldBeSkipped(metric.getMetricName())) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Skipping %s metric from being aggregated", metric.getMetricName()));
}
continue;
}
List<Long[]> timeSlices = getTimeSlices(getRoundedCheckPointTimeMillis(metric.getMetricValues().firstKey(), cacheSliceIntervalMillis), metric.getMetricValues().lastKey(), cacheSliceIntervalMillis);
Map<TimelineClusterMetric, Double> slicedClusterMetrics = sliceFromTimelineMetric(metric, timeSlices, interpolationEnabled);
if (slicedClusterMetrics != null) {
for (Map.Entry<TimelineClusterMetric, Double> metricDoubleEntry : slicedClusterMetrics.entrySet()) {
MetricClusterAggregate newMetricClusterAggregate = new MetricClusterAggregate(
metricDoubleEntry.getValue(), 1, null, metricDoubleEntry.getValue(), metricDoubleEntry.getValue());
//put app metric into cache
putMetricIntoCache(metricDoubleEntry.getKey(), newMetricClusterAggregate);
if (hostMetadata != null) {
//calculate app host metric
if (metric.getAppId().equalsIgnoreCase(HOST_APP_ID)) {
// Candidate metric, update app aggregates
if (hostMetadata.containsKey(metric.getHostName())) {
updateAppAggregatesFromHostMetric(metricDoubleEntry.getKey(), newMetricClusterAggregate, hostMetadata.get(metric.getHostName()));
}
} else {
// Build the hostedapps map if not a host metric
// Check app candidacy for host aggregation
//TODO better to lock TimelineMetricHostMetadata instance to avoid dataloss, but generally the data could be lost only during initial collector start
if (appIdsToAggregate.contains(metric.getAppId())) {
TimelineMetricHostMetadata timelineMetricHostMetadata = hostMetadata.get(metric.getHostName());
ConcurrentHashMap<String, String> appIdsMap;
if (timelineMetricHostMetadata == null) {
appIdsMap = new ConcurrentHashMap<>();
hostMetadata.put(metric.getHostName(), new TimelineMetricHostMetadata(appIdsMap));
} else {
appIdsMap = timelineMetricHostMetadata.getHostedApps();
}
if (!appIdsMap.containsKey(metric.getAppId())) {
appIdsMap.put(metric.getAppId(), metric.getAppId());
LOG.info("Adding appId to hosted apps: appId = " +
metric.getAppId() + ", hostname = " + metric.getHostName());
}
}
}
}
}
}
}
}
/**
* Get driver by name. If no driver discovered it will be created using
* custom capabilities and selenium server.
*
* @param name
* String driver name
* @param capabilities
* DesiredCapabilities
* @param seleniumHost
* String
* @return WebDriver
*/
default public WebDriver getDriver(String name, DesiredCapabilities capabilities, String seleniumHost) {
WebDriver drv = null;
ConcurrentHashMap<String, CarinaDriver> currentDrivers = getDrivers();
if (currentDrivers.containsKey(name)) {
CarinaDriver cdrv = currentDrivers.get(name);
drv = cdrv.getDriver();
if (Phase.BEFORE_SUITE.equals(cdrv.getPhase())) {
POOL_LOGGER.info("Before suite registered driver will be returned.");
} else {
POOL_LOGGER.debug(cdrv.getPhase() + " registered driver will be returned.");
}
}
// Long threadId = Thread.currentThread().getId();
// ConcurrentHashMap<String, WebDriver> currentDrivers = getDrivers();
// TODO [VD] do we really need finding by groupThreads?
/*
* if (currentDrivers.containsKey(name)) { drv =
* currentDrivers.get(name); } else if
* (Configuration.getInt(Parameter.THREAD_COUNT) == 1 &&
* Configuration.getInt(Parameter.DATA_PROVIDER_THREAD_COUNT) <= 1) {
* Thread[] threads =
* getGroupThreads(Thread.currentThread().getThreadGroup());
* logger.debug(
* "Try to find driver by ThreadGroup id values! Current ThreadGroup count is: "
* + threads.length); for (int i = 0; i < threads.length; i++) {
* currentDrivers = drivers.get(threads[i].getId()); if (currentDrivers
* != null) { if (currentDrivers.containsKey(name)) { drv =
* currentDrivers.get(name);
* logger.debug("########## GET ThreadGroupId: " + threadId +
* "; driver: " + drv); break; } } } }
*/
if (drv == null) {
POOL_LOGGER.debug("Starting new driver as nothing was found in the pool");
drv = createDriver(name, capabilities, seleniumHost);
}
// [VD] do not wrap EventFiringWebDriver here otherwise DriverListener
// and all logging will be lost!
return drv;
}