Java Code Examples for java.util.concurrent.ConcurrentHashMap.containsKey()

The following are Jave code examples for showing how to use containsKey() of the java.util.concurrent.ConcurrentHashMap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: tomcat7   File: StatementCache.java   View Source Code Vote up 7 votes
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;
    }
}
 
Example 2
Project: PraFramework   File: EventManager.java   View Source Code Vote up 7 votes
/**
 * Invokes all event listeners for the type of this given event instance with the given event instance
 * @param event the event instance
 */
public void callEvent(Event event) {
    ConcurrentHashMap<EventPrio, ArrayList<Listener>> listeners = eventListener.getOrDefault(event.getClass().getName(), new ConcurrentHashMap<>());

    if (listeners.containsKey(EventPrio.LOWEST))
        listeners.get(EventPrio.LOWEST).forEach(listener -> listener.invoke(event));

    if (listeners.containsKey(EventPrio.LOW))
        listeners.get(EventPrio.LOW).forEach(listener -> listener.invoke(event));

    if (listeners.containsKey(EventPrio.NORMAL))
        listeners.get(EventPrio.NORMAL).forEach(listener -> listener.invoke(event));

    if (listeners.containsKey(EventPrio.HIGH))
        listeners.get(EventPrio.HIGHEST).forEach(listener -> listener.invoke(event));

    if (listeners.containsKey(EventPrio.HIGHEST))
        listeners.get(EventPrio.HIGHEST).forEach(listener -> listener.invoke(event));
}
 
Example 3
Project: apache-tomcat-7.0.73-with-comment   File: StatementCache.java   View Source Code Vote up 7 votes
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;
    }
}
 
Example 4
Project: NYBus   File: NYBusDriver.java   View Source Code Vote up 7 votes
/**
 * Is target registered.
 *
 * @param targetObject    the target object.
 * @param targetChannelId the target channel id.
 * @return is target registered.
 */
private boolean isTargetRegistered(Object targetObject, List<String> targetChannelId) {
    Set<String> currentlyRegisteredChannelId = new HashSet<>();
    for (Map.Entry<Class<?>, ConcurrentHashMap<Object, ConcurrentHashMap<String,
            SubscriberHolder>>> mEventsToTargetsMapEntry : mEventsToTargetsMap.entrySet()) {
        ConcurrentHashMap<Object, ConcurrentHashMap<String, SubscriberHolder>> mTargetMap =
                mEventsToTargetsMapEntry.getValue();
        if (mTargetMap.containsKey(targetObject)) {
            ConcurrentHashMap<String, SubscriberHolder> subscribeMethods = mTargetMap.get
                    (targetObject);
            for (Map.Entry<String, SubscriberHolder> subscribeMethodEntry : subscribeMethods.entrySet()) {
                for (String methodChannelID : subscribeMethodEntry.getValue().subscribedChannelID) {
                    currentlyRegisteredChannelId.add(methodChannelID);

                }
            }
        }
    }
    return currentlyRegisteredChannelId.size() > 0 && currentlyRegisteredChannelId.containsAll(targetChannelId);
}
 
Example 5
Project: LiQ   File: MessageQueueHolder.java   View Source Code Vote up 6 votes
private void putMessageQueue(String topic, Integer queueId, MessageQueueValue value) {
    if (!mqMap.containsKey(topic)) {
        mqMap.put(topic, new ConcurrentHashMap<>());
    }
    ConcurrentHashMap<Integer, MessageQueueValue> queueMap = mqMap.get(topic);
    if (!queueMap.containsKey(queueId)) {
        queueMap.put(queueId, value);
    }
}
 
Example 6
Project: odoxSync   File: ClientMetadataReceivedInspector.java   View Source Code Vote up 6 votes
@Override
public void inspectRegion(Region region) {
    count++;

    ConcurrentHashMap<Long, Region> clientFileRegions = clientFile.getRegions();
    if(clientFileRegions.containsKey(region.getOffset())){
       receivedCount++;
    }
}
 
Example 7
Project: reading-and-annotate-rocketmq-3.4.6   File: ConsumerManager.java   View Source Code Vote up 6 votes
public HashSet<String> queryTopicConsumeByWho(final String topic) {
    HashSet<String> groups = new HashSet<String>();
    Iterator<Entry<String, ConsumerGroupInfo>> it = this.consumerTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, ConsumerGroupInfo> entry = it.next();
        ConcurrentHashMap<String, SubscriptionData> subscriptionTable =
                entry.getValue().getSubscriptionTable();
        if (subscriptionTable.containsKey(topic)) {
            groups.add(entry.getKey());
        }
    }

    return groups;
}
 
Example 8
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 6 votes
/**
 * containsKey(null) throws NPE
 */
public void testContainsKey_NullPointerException() {
    ConcurrentHashMap c = new ConcurrentHashMap(5);
    try {
        c.containsKey(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 9
Project: doctorkafka   File: ReplicaStatsManager.java   View Source Code Vote up 6 votes
public static void updateReplicaReassignmentTimestamp(String brokerZkUrl,
                                                       ReplicaStat replicaStat) {
  if (!replicaReassignmentTimestamps.containsKey(brokerZkUrl)) {
    replicaReassignmentTimestamps.put(brokerZkUrl, new ConcurrentHashMap<>());
  }
  ConcurrentHashMap<TopicPartition, Long> replicaTimestamps =
      replicaReassignmentTimestamps.get(brokerZkUrl);
  TopicPartition topicPartition = new TopicPartition(
      replicaStat.getTopic(), replicaStat.getPartition());

  if (!replicaTimestamps.containsKey(topicPartition) ||
      replicaTimestamps.get(topicPartition) < replicaStat.getTimestamp()) {
    replicaTimestamps.put(topicPartition, replicaStat.getTimestamp());
  }
}
 
Example 10
Project: doctorkafka   File: ReplicaStatsManager.java   View Source Code Vote up 6 votes
private static long getLastReplicaReassignmentTimestamp(String brokerZkUrl,
                                                        TopicPartition topicPartition) {
  long result = 0;
  if (replicaReassignmentTimestamps.containsKey(brokerZkUrl)) {
    ConcurrentHashMap<TopicPartition, Long> replicaTimestamps =
        replicaReassignmentTimestamps.get(brokerZkUrl);
    if (replicaTimestamps.containsKey(topicPartition)) {
      result = replicaTimestamps.get(topicPartition);
    }
  }
  return result;
}
 
Example 11
Project: rmq4note   File: ConsumerManager.java   View Source Code Vote up 6 votes
public HashSet<String> queryTopicConsumeByWho(final String topic) {
    HashSet<String> groups = new HashSet<>();
    Iterator<Entry<String, ConsumerGroupInfo>> it = this.consumerTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, ConsumerGroupInfo> entry = it.next();
        ConcurrentHashMap<String, SubscriptionData> subscriptionTable =
            entry.getValue().getSubscriptionTable();
        if (subscriptionTable.containsKey(topic)) {
            groups.add(entry.getKey());
        }
    }
    return groups;
}
 
Example 12
Project: NYBus   File: NYBusDriver.java   View Source Code Vote up 6 votes
/**
 * Add methods in target map.
 *
 * @param targetObject          the target object.
 * @param subscribeMethodHolder the subscribeMethodHolder.
 */
private void addOrUpdateMethodsInTargetMap(Object targetObject,
                                           SubscriberHolder subscribeMethodHolder) {
    ConcurrentHashMap<Object, ConcurrentHashMap<String, SubscriberHolder>> mTargetMap =
            mEventsToTargetsMap.get(subscribeMethodHolder.subscribedMethod.
                    getParameterTypes()[0]);
    if (mTargetMap != null) {
        if (mTargetMap.containsKey(targetObject)) {
            updateMethodInSet(targetObject, subscribeMethodHolder, mTargetMap);
        } else {
            addEntryInTargetMap(targetObject, subscribeMethodHolder, mTargetMap);
        }
    }
}
 
Example 13
Project: Limitart   File: JarScriptLoader.java   View Source Code Vote up 5 votes
private AbstractScriptLoader<KEY> loadScriptsByJar(String jarName)
		throws ClassNotFoundException, IOException, InstantiationException, IllegalAccessException, ScriptException,
		NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
	File file = new File(jarName);
	if (!file.exists()) {
		throw new IOException("file not exist:" + jarName);
	}
	// 这里要用系统自带的loader,不然会造成代码权限和作用域的问题
	URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
	Method add = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
	add.setAccessible(true);
	add.invoke(classLoader, new Object[] { file.toURI().toURL() });
	ConcurrentHashMap<KEY, IScript<KEY>> scriptMap_new = new ConcurrentHashMap<KEY, IScript<KEY>>();
	try (JarFile jarFile = new JarFile(file)) {
		Enumeration<JarEntry> entrys = jarFile.entries();
		while (entrys.hasMoreElements()) {
			JarEntry jarEntry = entrys.nextElement();
			String entryName = jarEntry.getName();
			if (entryName.endsWith(".class")) {
				String className = entryName.replace("/", ".").substring(0, entryName.indexOf(".class"));
				Class<?> clazz = classLoader.loadClass(className);
				log.info("load class:" + className);
				if (clazz == null) {
					throw new ScriptException("class not found:" + className);
				}
				if (className.contains("$")) {
					continue;
				}
				Object newInstance = clazz.newInstance();
				if (newInstance instanceof IScript) {
					if (newInstance instanceof IDynamicCode) {
						continue;
					}
					@SuppressWarnings("unchecked")
					IScript<KEY> script = (IScript<KEY>) newInstance;
					KEY scriptId = script.getScriptId();
					if (scriptMap_new.containsKey(scriptId)) {
						log.error("script id duplicated,source:" + scriptPath.get(scriptId).getName() + ",yours:"
								+ clazz.getName());
					} else {
						scriptMap_new.put(scriptId, script);
						log.info("compile script success:" + clazz.getName());
					}
				} else {
					throw new ScriptException("script file must implement IScript:" + clazz.getName());
				}
			}
		}
		this.scriptMap = scriptMap_new;
	}
	return this;
}
 
Example 14
Project: Limitart   File: FileScriptLoader.java   View Source Code Vote up 5 votes
/**
 * 加载一个目录下对应的全部脚本(不会加载IDynamicCode相关)
 * 
 * @param dir
 * @param scriptTypes
 * @return
 * @throws IOException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws ScriptException
 */
public AbstractScriptLoader<KEY> loadScriptsBySourceDir(String dir, ScriptFileType... scriptTypes)
		throws IOException, InstantiationException, IllegalAccessException, ScriptException {
	ConcurrentHashMap<KEY, IScript<KEY>> scriptMap_new = new ConcurrentHashMap<>();
	ConcurrentHashMap<KEY, File> scriptPath_new = new ConcurrentHashMap<>();
	try (GroovyClassLoader loader = new GroovyClassLoader(ClassLoader.getSystemClassLoader());) {
		File dir_root = new File(dir);
		if (!dir_root.exists()) {
			throw new IOException("scripts root dir does not exist:" + dir);
		}
		if (!dir_root.isDirectory()) {
			throw new IOException("file is not dir:" + dir);
		}
		String[] types = null;
		if (scriptTypes != null && scriptTypes.length > 0) {
			types = new String[scriptTypes.length];
			for (int i = 0; i < scriptTypes.length; ++i) {
				types[i] = scriptTypes[i].getValue();
			}
		}
		List<File> result = FileUtil.getFiles(dir_root, types);
		for (File file : result) {
			Class<?> parseClass = loader.parseClass(file);
			Object newInstance = parseClass.newInstance();
			if (newInstance instanceof IScript) {
				if (newInstance instanceof IDynamicCode) {
					continue;
				}
				@SuppressWarnings("unchecked")
				IScript<KEY> script = (IScript<KEY>) newInstance;
				KEY scriptId = script.getScriptId();
				if (scriptMap_new.containsKey(scriptId)) {
					log.error("script id duplicated,source:" + scriptPath.get(scriptId).getName() + ",yours:"
							+ file.getName());
				} else {
					scriptMap_new.put(scriptId, script);
					scriptPath_new.put(scriptId, file);
					log.info("compile script success:" + file.getName());
				}
			} else {
				throw new ScriptException("script file must implement IScript:" + file.getName());
			}
		}
		this.scriptMap = scriptMap_new;
		this.scriptPath = scriptPath_new;
	}
	return this;
}
 
Example 15
Project: util4j   File: AbstractScriptFactory.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
	public final void loadAllClass(){
		if(isLoading)
		{
			return;
		}
		isLoading=true;
		classLoader = new ScriptClassLoader();
		final ConcurrentHashMap<Integer, Class<? extends T>> codeMap=new ConcurrentHashMap<Integer, Class<? extends T>>();
		for (Entry<String,ClassFile> entry : scriptFilePaths.entrySet()) 
		{
			ClassFile classFile = entry.getValue();
			try {
				Class<T> scriptClass=null;
				Class<?> clazz=loadClass(classLoader, classFile);
				if(clazz!=null)
				{//类型转换
					scriptClass=(Class<T>)clazz;
				}
				if(scriptClass!=null)
				{
					boolean isAbstract=Modifier.isAbstract(scriptClass.getModifiers());//是否是抽象类
					if(isAbstract)
					{//抽象类
//						_log.info("loaded abstractScript:" + classFile.getFilePath());
					}else
					{
						T script=scriptClass.newInstance();
						int code=script.getMessageCode();
						if(codeMap.containsKey(code))
						{//如果已经存在相同code的脚步则不加载
							_log.error("find Repeat code script,addingScript:"+script.getClass()+",existScript:"+codeMap.get(code));
						}else
						{
							_log.info("**********LoadRegistClass<" + classFile.getClassName()+">**********");
							codeMap.put(code,scriptClass);
							_log.info("loaded codeScript,code="+code+"(0x"+Integer.toHexString(code)+"),path=" + classFile.getFilePath());
						}
					}
					//如果相同脚步的类文件发生改变后可能code会不一致,所以即使有相同code的脚步依然要记录时间
					classFile.setLastModifyTime(new File(classFile.getFilePath()).lastModified());//更新时间
				}
			} catch (Exception e) {
				_log.error(e.getMessage(),e);
			}
		}
		this.codeMap.putAll(codeMap);
		isLoading=false;
	}
 
Example 16
Project: DAA_Converter   File: ReadHits.java   View Source Code Vote up 4 votes
public void add(Hit h, SparseString gi, int frame) {

		if (!hitMap.containsKey(gi))
			hitMap.put(gi, new ConcurrentHashMap<Integer, Vector<Hit>>());
		ConcurrentHashMap<Integer, Vector<Hit>> frameMap = hitMap.get(gi);

		if (!frameMap.containsKey(frame))
			frameMap.put(frame, new Vector<Hit>());
		Vector<Hit> hits = frameMap.get(frame);

		hits.add(h);

	}
 
Example 17
Project: tqdev-metrics   File: MetricRegistry.java   View Source Code Vote up 4 votes
/**
 * Checks for existence of a metric for a given type and key.
 *
 * @param type
 *            the type
 * @param key
 *            the key
 * @return true, if successful
 */
public boolean has(String type, String key) {
	ConcurrentHashMap<String, Object> map = values.get(type);
	if (map == null) {
		return false;
	}
	return map.containsKey(key);
}