当前位置: 首页>>代码示例>>Java>>正文


Java ConcurrentHashMap.putIfAbsent方法代码示例

本文整理汇总了Java中java.util.concurrent.ConcurrentHashMap.putIfAbsent方法的典型用法代码示例。如果您正苦于以下问题:Java ConcurrentHashMap.putIfAbsent方法的具体用法?Java ConcurrentHashMap.putIfAbsent怎么用?Java ConcurrentHashMap.putIfAbsent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.concurrent.ConcurrentHashMap的用法示例。


在下文中一共展示了ConcurrentHashMap.putIfAbsent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getQueryStats

import java.util.concurrent.ConcurrentHashMap; //导入方法依赖的package包/类
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;
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:22,代码来源:SlowQueryReport.java

示例2: addCachedBatchEnd

import java.util.concurrent.ConcurrentHashMap; //导入方法依赖的package包/类
protected void addCachedBatchEnd(MarkovVertex start, MarkovEdge e, MarkovVertex v,
                                 Statement catalog_stmt, int idx, PartitionSet partitions, PartitionSet past_partitions) {
    ConcurrentHashMap<MultiKey<String>, Pair<MarkovEdge, MarkovVertex>> m = cache_batchEnd.get(start);
    if (m == null) {
        synchronized (this.cache_batchEnd) {
            m = this.cache_batchEnd.get(start);
            if (m == null) {
                m = new ConcurrentHashMap<MultiKey<String>, Pair<MarkovEdge, MarkovVertex>>();
                this.cache_batchEnd.put(start, m);
            }
        } // SYNCH
    }
    MultiKey<String> cache_key = new MultiKey<String>(CatalogKey.createKey(catalog_stmt),
                                                      Integer.toString(idx),
                                                      partitions.toString(),
                                                      past_partitions.toString());
    m.putIfAbsent(cache_key, Pair.of(e, v));
}
 
开发者ID:s-store,项目名称:sstore-soft,代码行数:19,代码来源:MarkovEstimator.java

示例3: calculateForSize

import java.util.concurrent.ConcurrentHashMap; //导入方法依赖的package包/类
public static void calculateForSize(File file, long fileSize) {
    file.setSize(fileSize);

    ConcurrentHashMap<Long, Region> regions = file.getRegions();

    long position = 0;
    do {

        long regionSize =
                position + REGION_SIZE > fileSize
                        ? fileSize - position
                        : REGION_SIZE;
        regions.putIfAbsent(position, new Region(position, regionSize));

        position += REGION_SIZE;
    } while (position < fileSize);
}
 
开发者ID:gaganis,项目名称:odoxSync,代码行数:18,代码来源:RegionCalculator.java

示例4: putIfAbsent

import java.util.concurrent.ConcurrentHashMap; //导入方法依赖的package包/类
/**
 * Associates given value {@code v} with this ClassLoaderValue and given
 * ClassLoader and returns {@code null} if there was no previously associated
 * value or does nothing and returns previously associated value if there
 * was one.
 *
 * @param cl the ClassLoader for the associated value
 * @param v  the value to associate
 * @return previously associated value or null if there was none
 */
public V putIfAbsent(ClassLoader cl, V v) {
    ConcurrentHashMap<CLV, Object> map = map(cl);
    @SuppressWarnings("unchecked")
    CLV clv = (CLV) this;
    while (true) {
        try {
            Object val = map.putIfAbsent(clv, v);
            return extractValue(val);
        } catch (Memoizer.RecursiveInvocationException e) {
            // propagate RecursiveInvocationException for the same key that
            // is just being calculated in computeIfAbsent
            throw e;
        } catch (Throwable t) {
            // don't propagate exceptions thrown from foreign Memoizer -
            // pretend that there was no entry and retry
            // (foreign computeIfAbsent invocation will try to remove it anyway)
        }
        // TODO:
        // Thread.onSpinLoop(); // when available
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:32,代码来源:AbstractClassLoaderValue.java

示例5: testGenericComparable

import java.util.concurrent.ConcurrentHashMap; //导入方法依赖的package包/类
/**
 * 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);
        assertNull(m.putIfAbsent(bis, true));
        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))));
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:24,代码来源:ConcurrentHashMapTest.java

示例6: getMessageQueue

import java.util.concurrent.ConcurrentHashMap; //导入方法依赖的package包/类
/**
 * get message queue or create message queue if not found
 *
 * @param topic
 * @param queueId
 * @return {@link MessageQueue} or new one
 */
public MessageQueue getMessageQueue(String topic, Integer queueId) {
    ConcurrentHashMap<Integer, MessageQueueValue> topicMQ = mqMap.get(topic);
    if (topicMQ == null) {
        ConcurrentHashMap<Integer, MessageQueueValue> newTopicMQ = new ConcurrentHashMap<>();
        ConcurrentHashMap<Integer, MessageQueueValue> oldTopicMQ = mqMap.putIfAbsent(topic, newTopicMQ);
        if (oldTopicMQ != null) {
            topicMQ = oldTopicMQ;
        } else {
            topicMQ = newTopicMQ;
        }
    }
    MessageQueueValue value = null;
    MessageQueueValue oldValue = topicMQ.putIfAbsent(queueId, new MessageQueueValue());
    if (oldValue != null) {
        value = oldValue;
    } else {
        value = topicMQ.get(queueId);
        topicMQ.get(queueId);
    }
    if (value.getMessageQueue() == null) {
        synchronized (value) {
            if (value.getMessageQueue() == null) {
                value.setMessageQueue(newMessageQueue(topic,
                        queueId,
                        storeConfig));
            }
        }
    }
    return value.getMessageQueue();
}
 
开发者ID:taobaorun,项目名称:LiQ,代码行数:38,代码来源:MessageQueueHolder.java

示例7: findConsumeQueue

import java.util.concurrent.ConcurrentHashMap; //导入方法依赖的package包/类
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;
}
 
开发者ID:y123456yz,项目名称:reading-and-annotate-rocketmq-3.4.6,代码行数:32,代码来源:Store.java

示例8: findConsumeQueue

import java.util.concurrent.ConcurrentHashMap; //导入方法依赖的package包/类
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;
}
 
开发者ID:y123456yz,项目名称:reading-and-annotate-rocketmq-3.4.6,代码行数:33,代码来源:DefaultMessageStore.java

示例9: testPutifAbsent

import java.util.concurrent.ConcurrentHashMap; //导入方法依赖的package包/类
@Test
public void testPutifAbsent(){
	ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>();
	map.put("key1", "value1");
	String v2 = map.putIfAbsent("key2", "value2");
	Assert.assertNull(v2);
	String v1 = map.putIfAbsent("key1", "otherValue");
	Assert.assertEquals(v1, "value1");;
}
 
开发者ID:jweixin,项目名称:jwx,代码行数:10,代码来源:TimeTest.java

示例10: doSubscribe

import java.util.concurrent.ConcurrentHashMap; //导入方法依赖的package包/类
@Override
protected void doSubscribe(final URL url, final NotifyListener listener) {
    try {
        clientLock.lock();

        ConcurrentHashMap<NotifyListener, IZkChildListener> childChangeListeners = serviceListeners.get(url);
        if (childChangeListeners == null) {
            serviceListeners.putIfAbsent(url, new ConcurrentHashMap<NotifyListener, IZkChildListener>());
            childChangeListeners = serviceListeners.get(url);
        }
        IZkChildListener zkChildListener = childChangeListeners.get(listener);
        if (zkChildListener == null) {
            childChangeListeners.putIfAbsent(listener, new IZkChildListener() {
                @Override
                public void handleChildChange(String parentPath, List<String> currentChilds) {

                    listener.notify(getUrl(), childrenNodeToUrls(parentPath, currentChilds));
                    logger.info(String.format("[ZookeeperRegistry] service list change: path=%s, currentChilds=%s", parentPath, currentChilds.toString()));
                }
            });
            zkChildListener = childChangeListeners.get(listener);
        }

        // 防止旧节点未正常注销
        removeNode(url, ZkNodeType.CLIENT);
        createNode(url, ZkNodeType.CLIENT);

        String serverTypePath = ZkUtils.toNodeTypePath(url, ZkNodeType.SERVER);
        zkClient.subscribeChildChanges(serverTypePath, zkChildListener);
        logger.info(String.format("[ZookeeperRegistry] subscribe service: path=%s, info=%s", ZkUtils.toNodePath(url, ZkNodeType.SERVER), url.toFullUri()));
    } catch (Throwable e) {
        throw new RpcFrameworkException(String.format("Failed to subscribe %s to zookeeper(%s), cause: %s", url, getUrl(), e.getMessage()), e);
    } finally {
        clientLock.unlock();
    }
}
 
开发者ID:TFdream,项目名称:mango,代码行数:37,代码来源:ZookeeperRegistry.java

示例11: testPutIfAbsent1_NullPointerException

import java.util.concurrent.ConcurrentHashMap; //导入方法依赖的package包/类
/**
 * putIfAbsent(null, x) throws NPE
 */
public void testPutIfAbsent1_NullPointerException() {
    ConcurrentHashMap c = new ConcurrentHashMap(5);
    try {
        c.putIfAbsent(null, "whatever");
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:11,代码来源:ConcurrentHashMapTest.java

示例12: testPutIfAbsent2_NullPointerException

import java.util.concurrent.ConcurrentHashMap; //导入方法依赖的package包/类
/**
 * putIfAbsent(x, null) throws NPE
 */
public void testPutIfAbsent2_NullPointerException() {
    ConcurrentHashMap c = new ConcurrentHashMap(5);
    try {
        c.putIfAbsent("whatever", null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:11,代码来源:ConcurrentHashMapTest.java

示例13: findConsumeQueue

import java.util.concurrent.ConcurrentHashMap; //导入方法依赖的package包/类
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;
}
 
开发者ID:lyy4j,项目名称:rmq4note,代码行数:30,代码来源:Store.java

示例14: findConsumeQueue

import java.util.concurrent.ConcurrentHashMap; //导入方法依赖的package包/类
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;
}
 
开发者ID:lyy4j,项目名称:rmq4note,代码行数:31,代码来源:DefaultMessageStore.java

示例15: findRelationsRecursively

import java.util.concurrent.ConcurrentHashMap; //导入方法依赖的package包/类
private ListenableFuture<Set<EntityRelation>> findRelationsRecursively(final EntityId rootId, final EntitySearchDirection direction, int lvl,
                                                                       final ConcurrentHashMap<EntityId, Boolean> uniqueMap) throws Exception {
    if (lvl == 0) {
        return Futures.immediateFuture(Collections.emptySet());
    }
    lvl--;
    //TODO: try to remove this blocking operation
    Set<EntityRelation> children = new HashSet<>(findRelations(rootId, direction).get());
    Set<EntityId> childrenIds = new HashSet<>();
    for (EntityRelation childRelation : children) {
        log.info("Found Relation: {}", childRelation);
        EntityId childId;
        if (direction == EntitySearchDirection.FROM) {
            childId = childRelation.getTo();
        } else {
            childId = childRelation.getFrom();
        }
        if (uniqueMap.putIfAbsent(childId, Boolean.TRUE) == null) {
            log.info("Adding Relation: {}", childId);
            if (childrenIds.add(childId)) {
                log.info("Added Relation: {}", childId);
            }
        }
    }
    List<ListenableFuture<Set<EntityRelation>>> futures = new ArrayList<>();
    for (EntityId entityId : childrenIds) {
        futures.add(findRelationsRecursively(entityId, direction, lvl, uniqueMap));
    }
    //TODO: try to remove this blocking operation
    List<Set<EntityRelation>> relations = Futures.successfulAsList(futures).get();
    relations.forEach(r -> r.forEach(d -> children.add(d)));
    return Futures.immediateFuture(children);
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:34,代码来源:BaseRelationService.java


注:本文中的java.util.concurrent.ConcurrentHashMap.putIfAbsent方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。