下面列出了java.util.concurrent.ConcurrentHashMap#putIfAbsent ( ) 实例代码,或者点击链接到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;
}
/**
* Atomically gets an existing MetricProxy from the given cache or creates a new one and adds it.
*
* @param cache The Cache to get or insert into.
* @param name Metric/Proxy name.
* @param createMetric A Function that creates a new Metric given its name.
* @param createProxy A Function that creates a MetricProxy given its input.
* @param <T> Type of Metric.
* @param <V> Type of MetricProxy.
* @return Either the existing MetricProxy (if it is already registered) or the newly created one.
*/
private <T extends Metric, V extends MetricProxy<T>> V getOrSet(ConcurrentHashMap<String, V> cache, String name,
Function<String, T> createMetric,
ProxyCreator<T, V> createProxy, String... tags) {
// We could simply use Map.computeIfAbsent to do everything atomically, however in ConcurrentHashMap, the function
// is evaluated while holding the lock. As per the method's guidelines, the computation should be quick and not
// do any IO or acquire other locks, however we have no control over new Metric creation. As such, we use optimistic
// concurrency, where we assume that the MetricProxy does not exist, create it, and then if it does exist, close
// the newly created one.
MetricsNames.MetricKey keys = metricKey(name, tags);
T newMetric = createMetric.apply(keys.getRegistryKey());
V newProxy = createProxy.apply(newMetric, keys.getCacheKey(), cache::remove);
V existingProxy = cache.putIfAbsent(newProxy.getProxyName(), newProxy);
if (existingProxy != null) {
newProxy.close();
newMetric.close();
return existingProxy;
} else {
return newProxy;
}
}
/**
* 创建一个记录对象, 或者返回缓存中已有的记录。
*/
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);
}
}
/**
* @param key the lookup key for the provided map, typically a region code or a country calling
* code
* @param map the map containing mappings of already loaded metadata from their {@code key}. If
* this {@code key}'s metadata isn't already loaded, it will be added to this map after
* loading
* @param filePrefix the prefix of the file to load metadata from
*/
<T> PhoneMetadata getMetadataFromMultiFilePrefix(T key,
ConcurrentHashMap<T, PhoneMetadata> map, String filePrefix) {
PhoneMetadata metadata = map.get(key);
if (metadata != null) {
return metadata;
}
// We assume key.toString() is well-defined.
String fileName = filePrefix + "_" + key;
List<PhoneMetadata> metadataList = getMetadataFromSingleFileName(fileName, metadataLoader);
if (metadataList.size() > 1) {
logger.log(Level.WARNING, "more than one metadata in file " + fileName);
}
metadata = metadataList.get(0);
PhoneMetadata oldValue = map.putIfAbsent(key, metadata);
return (oldValue != null) ? oldValue : metadata;
}
/**
* Elements of classes with erased generic type parameters based
* on Comparable can be inserted and found.
*/
public void testGenericComparable() {
int size = 120; // makes measured test run time -> 60ms
ConcurrentHashMap<Object, Boolean> m =
new ConcurrentHashMap<Object, Boolean>();
for (int i = 0; i < size; i++) {
BI bi = new BI(i);
BS bs = new BS(String.valueOf(i));
LexicographicList<BI> bis = new LexicographicList<BI>(bi);
LexicographicList<BS> bss = new LexicographicList<BS>(bs);
assertTrue(m.putIfAbsent(bis, true) == null);
assertTrue(m.containsKey(bis));
if (m.putIfAbsent(bss, true) == null)
assertTrue(m.containsKey(bss));
assertTrue(m.containsKey(bis));
}
for (int i = 0; i < size; i++) {
assertTrue(m.containsKey(Collections.singletonList(new BI(i))));
}
}
public static TableExtensionHolder getInstance(SiddhiAppContext siddhiAppContext) {
ConcurrentHashMap<Class, AbstractExtensionHolder> extensionHolderMap = siddhiAppContext.getSiddhiContext
().getExtensionHolderMap();
AbstractExtensionHolder abstractExtensionHolder = extensionHolderMap.get(clazz);
if (abstractExtensionHolder == null) {
abstractExtensionHolder = new TableExtensionHolder(siddhiAppContext);
extensionHolderMap.putIfAbsent(clazz, abstractExtensionHolder);
}
return (TableExtensionHolder) extensionHolderMap.get(clazz);
}
public ConsumeQueue findConsumeQueue(String topic, int queueId) {
ConcurrentHashMap<Integer, ConsumeQueue> map = consumeQueueTable.get(topic);
if (null == map) {
ConcurrentHashMap<Integer, ConsumeQueue> newMap = new ConcurrentHashMap<Integer, ConsumeQueue>(128);
ConcurrentHashMap<Integer, ConsumeQueue> oldMap = consumeQueueTable.putIfAbsent(topic, newMap);
if (oldMap != null) {
map = oldMap;
} else {
map = newMap;
}
}
ConsumeQueue logic = map.get(queueId);
if (null == logic) {
ConsumeQueue newLogic = new ConsumeQueue(//
topic, //
queueId, //
StorePathConfigHelper.getStorePathConsumeQueue(this.messageStoreConfig.getStorePathRootDir()), //
this.getMessageStoreConfig().getMapedFileSizeConsumeQueue(), //
this);
ConsumeQueue oldLogic = map.putIfAbsent(queueId, newLogic);
if (oldLogic != null) {
logic = oldLogic;
} else {
logic = newLogic;
}
}
return logic;
}
@Test
public void testSingle() throws SQLException, InterruptedException {
final ConcurrentHashMap<String, Object> ids = new ConcurrentHashMap<>();
final Object v = new Object();
TransactionIdGenerator g = new TransactionIdGenerator();
for(int i = 0; i<1000; i++) {
String id = g.getNextId("test", "ph-1", "0", "worker", "worker").getUniqueId();
// System.out.println(id);
if(ids.putIfAbsent(id, v) != null) {
fail();
}
}
}
public ConsumeQueue findConsumeQueue(String topic, int queueId) {
ConcurrentHashMap<Integer, ConsumeQueue> map = consumeQueueTable.get(topic);
if (null == map) {
ConcurrentHashMap<Integer, ConsumeQueue> newMap =
new ConcurrentHashMap<Integer, ConsumeQueue>(128);
ConcurrentHashMap<Integer, ConsumeQueue> oldMap = consumeQueueTable.putIfAbsent(topic, newMap);
if (oldMap != null) {
map = oldMap;
}
else {
map = newMap;
}
}
ConsumeQueue logic = map.get(queueId);
if (null == logic) {
ConsumeQueue newLogic = new ConsumeQueue(//
topic,//
queueId,//
StorePathConfigHelper.getStorePathConsumeQueue(lStorePath),//
lSize,//
null);
ConsumeQueue oldLogic = map.putIfAbsent(queueId, newLogic);
if (oldLogic != null) {
logic = oldLogic;
}
else {
logic = newLogic;
}
}
return logic;
}
@Override
public void onNext(HttpSourceEvent event) {
sourceEventCounters.putIfAbsent(event.getEventType(), new AtomicInteger());
sourceEventCounters.get(event.getEventType()).incrementAndGet();
ConcurrentHashMap<ServerInfo, AtomicInteger> counters = serverEventCounters.get(event.getEventType());
counters.putIfAbsent(event.getServer(), new AtomicInteger());
counters.get(event.getServer()).incrementAndGet();
System.out.println(String.format("Event: %s for server %s:%s", event.getEventType(), event.getServer().getHost(), event.getServer().getPort()));
}
/**
* putIfAbsent(null, x) throws NPE
*/
public void testPutIfAbsent1_NullPointerException() {
ConcurrentHashMap c = new ConcurrentHashMap(5);
try {
c.putIfAbsent(null, "whatever");
shouldThrow();
} catch (NullPointerException success) {}
}
private static void testForEach() {
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
map.putIfAbsent("foo", "bar");
map.putIfAbsent("han", "solo");
map.putIfAbsent("r2", "d2");
map.putIfAbsent("c3", "p0");
map.forEach(1, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName()));
// map.forEach(5, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName()));
System.out.println(map.mappingCount());
}
private static void testSearch() {
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
map.putIfAbsent("foo", "bar");
map.putIfAbsent("han", "solo");
map.putIfAbsent("r2", "d2");
map.putIfAbsent("c3", "p0");
System.out.println("\nsearch()\n");
String result1 = map.search(1, (key, value) -> {
System.out.println(Thread.currentThread().getName());
if (key.equals("foo") && value.equals("bar")) {
return "foobar";
}
return null;
});
System.out.println(result1);
System.out.println("\nsearchValues()\n");
String result2 = map.searchValues(1, value -> {
System.out.println(Thread.currentThread().getName());
if (value.length() > 3) {
return value;
}
return null;
});
System.out.println(result2);
}
public ConsumeQueue findConsumeQueue(String topic, int queueId) {
ConcurrentHashMap<Integer, ConsumeQueue> map = consumeQueueTable.get(topic);
if (null == map) {
ConcurrentHashMap<Integer, ConsumeQueue> newMap = new ConcurrentHashMap<Integer, ConsumeQueue>(128);
ConcurrentHashMap<Integer, ConsumeQueue> oldMap = consumeQueueTable.putIfAbsent(topic, newMap);
if (oldMap != null) {
map = oldMap;
}
else {
map = newMap;
}
}
ConsumeQueue logic = map.get(queueId);
if (null == logic) {
ConsumeQueue newLogic = new ConsumeQueue(//
topic,//
queueId,//
StorePathConfigHelper.getStorePathConsumeQueue(this.messageStoreConfig.getStorePathRootDir()),//
this.getMessageStoreConfig().getMapedFileSizeConsumeQueue(),//
this);
ConsumeQueue oldLogic = map.putIfAbsent(queueId, newLogic);
if (oldLogic != null) {
logic = oldLogic;
}
else {
logic = newLogic;
}
}
return logic;
}
private StackTraceNode getNode(StackTraceElement element, ConcurrentHashMap<String, StackTraceNode> nodes) {
String line = element.toString();
StackTraceNode node = nodes.get(line);
if(node != null)
return node;
node = new StackTraceNode(line);
StackTraceNode existingNode = nodes.putIfAbsent(line, node);
return existingNode == null ? node : existingNode;
}
@Override
@SuppressWarnings("unchecked")
public boolean registerBiz(Biz biz) {
AssertUtils.assertNotNull(biz, "Biz must not be null.");
AssertUtils.isTrue(biz.getBizState() == BizState.RESOLVED, "BizState must be RESOLVED.");
bizRegistration.putIfAbsent(biz.getBizName(), new ConcurrentHashMap<String, Biz>(16));
ConcurrentHashMap bizCache = bizRegistration.get(biz.getBizName());
return bizCache.putIfAbsent(biz.getBizVersion(), biz) == null;
}
/**
* compatible with jdk6
*/
private <T extends Metric> T computeIfAbsent(ConcurrentHashMap<Id, Metric> map, Id id,
NewMetricFunction<? extends Metric> f) {
Metric m = map.get(id);
if (m == null) {
//如果metrics过多了,则给个noop,并给出提示;
if (map.size() >= config.getInt(LOOKOUT_MAX_METRICS_NUMBER,
MetricConfig.DEFAULT_MAX_METRICS_NUM)) {
if (maxNumWarning) {
logger
.warn(
"metrics number reach max limit: {}! Do not record this new metric(id:{}).",
config.getInt(LOOKOUT_MAX_METRICS_NUMBER,
MetricConfig.DEFAULT_MAX_METRICS_NUM), id);
maxNumWarning = false;
}
return (T) f.noopMetric();
}
//if the key exists,this execution is useless!
Metric tmp = f.apply(id);
m = map.putIfAbsent(id, tmp);
if (m == null) {
//first register
m = tmp;
onMetricAdded(tmp);
}
}
return (T) m;
}
public ConsumeQueue findConsumeQueue(String topic, int queueId) {
ConcurrentHashMap<Integer, ConsumeQueue> map = consumeQueueTable.get(topic);
if (null == map) {
ConcurrentHashMap<Integer, ConsumeQueue> newMap =
new ConcurrentHashMap<Integer, ConsumeQueue>(128);
ConcurrentHashMap<Integer, ConsumeQueue> oldMap = consumeQueueTable.putIfAbsent(topic, newMap);
if (oldMap != null) {
map = oldMap;
} else {
map = newMap;
}
}
ConsumeQueue logic = map.get(queueId);
if (null == logic) {
ConsumeQueue newLogic = new ConsumeQueue(
topic,
queueId,
StorePathConfigHelper.getStorePathConsumeQueue(lStorePath),
lSize,
null);
ConsumeQueue oldLogic = map.putIfAbsent(queueId, newLogic);
if (oldLogic != null) {
logic = oldLogic;
} else {
logic = newLogic;
}
}
return logic;
}
/**
* putIfAbsent(x, null) throws NPE
*/
public void testPutIfAbsent2_NullPointerException() {
ConcurrentHashMap c = new ConcurrentHashMap(5);
try {
c.putIfAbsent("whatever", null);
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* putIfAbsent works when the given key is not present
*/
public void testPutIfAbsent() {
ConcurrentHashMap map = map5();
map.putIfAbsent(six, "Z");
assertTrue(map.containsKey(six));
}