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

The following examples show how to use java.util.concurrent.ConcurrentHashMap#putIfAbsent() . 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: ConcurrentHashMapTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * 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))));
    }
}
 
Example 2
Source File: SlowQueryReport.java    From tomcatsrc with Apache License 2.0 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 3
Source File: StatsLoggerProxy.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 4
Source File: SoftRefLogWriter.java    From tddl 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: MetadataManager.java    From libphonenumber-android with Apache License 2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example 6
Source File: ConcurrentHashMap1.java    From java8-tutorial with MIT License 5 votes vote down vote up
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);
}
 
Example 7
Source File: ConcurrentHashMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * putIfAbsent(x, null) throws NPE
 */
public void testPutIfAbsent2_NullPointerException() {
    ConcurrentHashMap c = new ConcurrentHashMap(5);
    try {
        c.putIfAbsent("whatever", null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 8
Source File: Store.java    From rocketmq_trans_message with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 9
Source File: AbstractRegistry.java    From sofa-lookout with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 10
Source File: BizManagerServiceImpl.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 11
Source File: StackTraceRecorder.java    From hollow with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 12
Source File: DefaultMessageStore.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 13
Source File: TableExtensionHolder.java    From siddhi with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 14
Source File: ConcurrentHashMap1.java    From java8-tutorial with MIT License 5 votes vote down vote up
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());
    }
 
Example 15
Source File: ConcurrentHashMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * putIfAbsent(null, x) throws NPE
 */
public void testPutIfAbsent1_NullPointerException() {
    ConcurrentHashMap c = new ConcurrentHashMap(5);
    try {
        c.putIfAbsent(null, "whatever");
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 16
Source File: TestSourceObserver.java    From mantis with Apache License 2.0 5 votes vote down vote up
@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()));
}
 
Example 17
Source File: Store.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 18
Source File: TransactionIdGeneratorTest.java    From das with Apache License 2.0 5 votes vote down vote up
@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();
            }
        }        
    }
 
Example 19
Source File: DefaultMessageStore.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 20
Source File: ConcurrentHashMapTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * putIfAbsent works when the given key is not present
 */
public void testPutIfAbsent() {
    ConcurrentHashMap map = map5();
    map.putIfAbsent(six, "Z");
    assertTrue(map.containsKey(six));
}