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

The following are Jave code examples for showing how to use putIfAbsent() 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: SlowQueryReport.java   View Source Code Vote up 8 votes
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 2
Project: sstore-soft   File: MarkovEstimator.java   View Source Code Vote up 7 votes
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));
}
 
Example 3
Project: odoxSync   File: RegionCalculator.java   View Source Code Vote up 7 votes
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);
}
 
Example 4
Project: s-store   File: MarkovEstimator.java   View Source Code Vote up 7 votes
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));
}
 
Example 5
Project: apache-tomcat-7.0.73-with-comment   File: SlowQueryReport.java   View Source Code Vote up 7 votes
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 6
Project: openjdk-jdk10   File: AbstractClassLoaderValue.java   View Source Code Vote up 7 votes
/**
 * 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
    }
}
 
Example 7
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 7 votes
/**
 * 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))));
    }
}
 
Example 8
Project: LiQ   File: MessageQueueHolder.java   View Source Code Vote up 6 votes
/**
 * 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();
}
 
Example 9
Project: reading-and-annotate-rocketmq-3.4.6   File: Store.java   View Source Code Vote up 6 votes
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 10
Project: reading-and-annotate-rocketmq-3.4.6   File: DefaultMessageStore.java   View Source Code Vote up 6 votes
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 11
Project: jwx   File: TimeTest.java   View Source Code Vote up 6 votes
@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");;
}
 
Example 12
Project: mango   File: ZookeeperRegistry.java   View Source Code Vote up 6 votes
@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();
    }
}
 
Example 13
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 6 votes
/**
 * putIfAbsent(null, x) throws NPE
 */
public void testPutIfAbsent1_NullPointerException() {
    ConcurrentHashMap c = new ConcurrentHashMap(5);
    try {
        c.putIfAbsent(null, "whatever");
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 14
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 6 votes
/**
 * putIfAbsent(x, null) throws NPE
 */
public void testPutIfAbsent2_NullPointerException() {
    ConcurrentHashMap c = new ConcurrentHashMap(5);
    try {
        c.putIfAbsent("whatever", null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 15
Project: rmq4note   File: Store.java   View Source Code Vote up 6 votes
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 16
Project: rmq4note   File: DefaultMessageStore.java   View Source Code Vote up 6 votes
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 17
Project: iotplatform   File: BaseRelationService.java   View Source Code Vote up 6 votes
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);
}
 
Example 18
Project: ditb   File: QuotaCache.java   View Source Code Vote up 6 votes
/**
 * Returns the QuotaState requested. If the quota info is not in cache an empty one will be
 * returned and the quota request will be enqueued for the next cache refresh.
 */
private <K> QuotaState
    getQuotaState(final ConcurrentHashMap<K, QuotaState> quotasMap, final K key) {
  QuotaState quotaInfo = quotasMap.get(key);
  if (quotaInfo == null) {
    quotaInfo = new QuotaState();
    if (quotasMap.putIfAbsent(key, quotaInfo) == null) {
      triggerCacheRefresh();
    }
  }
  return quotaInfo;
}
 
Example 19
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 5 votes
/**
 * putIfAbsent works when the given key is not present
 */
public void testPutIfAbsent() {
    ConcurrentHashMap map = map5();
    map.putIfAbsent(six, "Z");
    assertTrue(map.containsKey(six));
}