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

The following examples show how to use java.util.concurrent.ConcurrentHashMap#put() . 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: DistinctEntrySetElements.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final ConcurrentHashMap<String, String> concurrentHashMap =
        new ConcurrentHashMap<>();

    concurrentHashMap.put("One", "Un");
    concurrentHashMap.put("Two", "Deux");
    concurrentHashMap.put("Three", "Trois");

    Set<Map.Entry<String, String>> entrySet = concurrentHashMap.entrySet();
    HashSet<Map.Entry<String, String>> hashSet = new HashSet<>(entrySet);

    if (false == hashSet.equals(entrySet)) {
        throw new RuntimeException("Test FAILED: Sets are not equal.");
    }
    if (hashSet.hashCode() != entrySet.hashCode()) {
        throw new RuntimeException("Test FAILED: Set's hashcodes are not equal.");
    }
}
 
Example 2
Source File: IDriverPool.java    From carina with Apache License 2.0 6 votes vote down vote up
@Deprecated
public static ConcurrentHashMap<String, WebDriver> getStaticDrivers() {
    Long threadId = Thread.currentThread().getId();
    ConcurrentHashMap<String, WebDriver> currentDrivers = new ConcurrentHashMap<String, WebDriver>();
    for (CarinaDriver carinaDriver : driversPool) {
        if (Phase.BEFORE_SUITE.equals(carinaDriver.getPhase())) {
            POOL_LOGGER.debug("Add suite_mode drivers into the getStaticDrivers response: " + carinaDriver.getName());
            currentDrivers.put(carinaDriver.getName(), carinaDriver.getDriver());
        } else if (threadId.equals(carinaDriver.getThreadId())) {
            POOL_LOGGER.debug("Add driver into the getStaticDrivers response: " + carinaDriver.getName() + " by threadId: "
                    + threadId);
            currentDrivers.put(carinaDriver.getName(), carinaDriver.getDriver());
        }
    }
    return currentDrivers;
}
 
Example 3
Source File: ReportingWorkerTest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testFailure() {
    User user = new User();
    user.email = "test";
    user.appName = AppNameUtil.BLYNK;
    ReportingWorker reportingWorker = new ReportingWorker(reportingDaoMock,
            reportingFolder, new ReportingDBManager(blockingIOProcessor, true));

    ConcurrentHashMap<AggregationKey, AggregationValue> map = new ConcurrentHashMap<>();

    long ts = getTS() / AverageAggregatorProcessor.HOUR;

    AggregationKey aggregationKey = new AggregationKey("ddd\[email protected]",
            AppNameUtil.BLYNK, 1, 0, PinType.ANALOG, (short) 1, ts);
    AggregationValue aggregationValue = new AggregationValue();
    aggregationValue.update(100);

    map.put(aggregationKey, aggregationValue);

    when(averageAggregator.getMinute()).thenReturn(map);

    reportingWorker.run();
    assertTrue(map.isEmpty());
}
 
Example 4
Source File: CloudToStoreReplicationManager.java    From ambry with Apache License 2.0 6 votes vote down vote up
@Override
public void onInstanceConfigChange(List<InstanceConfig> instanceConfigs, NotificationContext context) {
  logger.info("Instance config change notification received with instanceConfigs: {}", instanceConfigs);
  Set<CloudDataNode> newVcrNodes = new HashSet<>();
  ConcurrentHashMap<String, CloudDataNode> newInstanceNameToCloudDataNode = new ConcurrentHashMap<>();

  // create a new list of available vcr nodes.
  for (InstanceConfig instanceConfig : instanceConfigs) {
    String instanceName = instanceConfig.getInstanceName();
    Port sslPort =
        getSslPortStr(instanceConfig) == null ? null : new Port(getSslPortStr(instanceConfig), PortType.SSL);
    Port http2Port =
        getHttp2PortStr(instanceConfig) == null ? null : new Port(getHttp2PortStr(instanceConfig), PortType.HTTP2);
    CloudDataNode cloudDataNode = new CloudDataNode(instanceConfig.getHostName(),
        new Port(Integer.parseInt(instanceConfig.getPort()), PortType.PLAINTEXT), sslPort, http2Port,
        clusterMapConfig.clustermapVcrDatacenterName, clusterMapConfig);
    newInstanceNameToCloudDataNode.put(instanceName, cloudDataNode);
    newVcrNodes.add(cloudDataNode);
  }

  synchronized (notificationLock) {
    instanceNameToCloudDataNode.set(newInstanceNameToCloudDataNode);
    handleChangeInVcrNodes(newVcrNodes);
  }
}
 
Example 5
Source File: ConcurrentHashMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * put(null,x) throws NPE
 */
public void testPut1_NullPointerException() {
    ConcurrentHashMap c = new ConcurrentHashMap(5);
    try {
        c.put(null, "whatever");
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 6
Source File: CategorySyncStatisticsTest.java    From commercetools-sync-java with Apache License 2.0 5 votes vote down vote up
@Test
void getMissingParentKey_OnANonEmptyList_ShouldReturnCorrectParentKeyInOptional() {
    final ConcurrentHashMap<String, Set<String>> categoryKeysWithMissingParents = new ConcurrentHashMap<>();
    final Set<String> existingChildrenKeys = new HashSet<>();
    existingChildrenKeys.add("key1");
    existingChildrenKeys.add("key2");

    final String existingParentKey = "existingParent";
    categoryKeysWithMissingParents.put(existingParentKey, existingChildrenKeys);
    categorySyncStatistics.setCategoryKeysWithMissingParents(categoryKeysWithMissingParents);

    assertThat(categorySyncStatistics.getMissingParentKey("key1")).contains(existingParentKey);
    assertThat(categorySyncStatistics.getMissingParentKey("key2")).contains(existingParentKey);
}
 
Example 7
Source File: CacheByTimeUtil.java    From SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 设置缓存(指定缓存有效时间)
 * @param key
 * @param value
 * @param validTime
 */
public static void setCache(String key,Object value,int validTime) {
    synchronized (key.intern()){
        if (StringUtils.isNotEmpty(key) && value != null){
            ConcurrentHashMap<Long,CacheValue> cache = CATCH.get(key);
            if (cache == null){
                cache = new ConcurrentHashMap<>();
            }
            cache.clear();
            cache.put(System.currentTimeMillis(),new CacheValue(validTime,value));
            CATCH.put(key,cache);
        }
    }
}
 
Example 8
Source File: WorkerProcessPoolTest.java    From buck with Apache License 2.0 5 votes vote down vote up
private static UnsafeRunnable borrowAndReturnWorkerProcess(
    WorkerProcessPool pool, ConcurrentHashMap<Thread, WorkerProcess> usedWorkers) {
  return () -> {
    try (BorrowedWorkerProcess worker = pool.borrowWorkerProcess()) {
      WorkerProcess workerProcess = worker.get();
      usedWorkers.put(Thread.currentThread(), workerProcess);
      workerProcess.ensureLaunchAndHandshake();
    }
  };
}
 
Example 9
Source File: CategorySyncStatisticsTest.java    From commercetools-sync-java with Apache License 2.0 5 votes vote down vote up
@Test
void getNumberOfCategoriesWithMissingParents_WithEmptyValue_ShouldReturn0() {
    final ConcurrentHashMap<String, Set<String>> categoryKeysWithMissingParents = new ConcurrentHashMap<>();
    categoryKeysWithMissingParents.put("parent2", emptySet());

    categorySyncStatistics.setCategoryKeysWithMissingParents(categoryKeysWithMissingParents);
    assertThat(categorySyncStatistics.getNumberOfCategoriesWithMissingParents()).isZero();
}
 
Example 10
Source File: ChannelServerJampRpc.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
void putLink(String address, ServiceRefAmp serviceRef)
{
  synchronized (this) {
    ConcurrentHashMap<String, ServiceRefAmp> linkMap = _linkServiceMap;
  
    if (linkMap == null) {
      linkMap = _linkServiceMap = new ConcurrentHashMap<>();
    }
    
    linkMap.put(address, serviceRef);
  }
}
 
Example 11
Source File: SunLayoutEngine.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
public LayoutEngine getEngine(LayoutEngineKey key) {
    ConcurrentHashMap<LayoutEngineKey, LayoutEngine> cache = cacheref.get();
    if (cache == null) {
        cache = new ConcurrentHashMap<>();
        cacheref = new SoftReference<>(cache);
    }

    LayoutEngine e = cache.get(key);
    if (e == null) {
        LayoutEngineKey copy = key.copy();
        e = new SunLayoutEngine(copy);
        cache.put(copy, e);
    }
    return e;
}
 
Example 12
Source File: HBaseTableConfig.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private synchronized void initMap() {
    if (tableMapping != null) {
        return;
    }
    ConcurrentHashMap<Pattern, HBaseTableInfo> tmp = new ConcurrentHashMap<>();
    for (HBaseTableInfo info : hbaseTables) {
        tmp.put(Pattern.compile(info.getOriginalTable()), info);
    }
    tableMapping = tmp;
}
 
Example 13
Source File: ConcurrentHashMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * remove(null) throws NPE
 */
public void testRemove1_NullPointerException() {
    ConcurrentHashMap c = new ConcurrentHashMap(5);
    c.put("sadsdf", "asdads");
    try {
        c.remove(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 14
Source File: ConcurrentHashMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * remove(null, x) throws NPE
 */
public void testRemove2_NullPointerException() {
    ConcurrentHashMap c = new ConcurrentHashMap(5);
    c.put("sadsdf", "asdads");
    try {
        c.remove(null, "whatever");
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 15
Source File: ConcurrentHashMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * remove(x, null) returns false
 */
public void testRemove3() {
    ConcurrentHashMap c = new ConcurrentHashMap(5);
    c.put("sadsdf", "asdads");
    assertFalse(c.remove("sadsdf", null));
}
 
Example 16
Source File: AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@DesireNoWarning("AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION")
void notBug2(ConcurrentHashMap anyMap1, ConcurrentHashMap anyMap2, Object anyKey, Object anyValue) {
    if (!anyMap1.containsKey(anyKey))
        anyMap2.put(anyKey, anyValue);
}
 
Example 17
Source File: RebalanceLockManager.java    From RocketMQ-Master-analyze with Apache License 2.0 4 votes vote down vote up
/**
 * 尝试锁队列
 * 
 * @return 是否lock成功
 */
public boolean tryLock(final String group, final MessageQueue mq, final String clientId) {
    // 没有被锁住
    if (!this.isLocked(group, mq, clientId)) {
        try {
            this.lock.lockInterruptibly();
            try {
                ConcurrentHashMap<MessageQueue, LockEntry> groupValue = this.mqLockTable.get(group);
                if (null == groupValue) {
                    groupValue = new ConcurrentHashMap<MessageQueue, LockEntry>(32);
                    this.mqLockTable.put(group, groupValue);
                }

                LockEntry lockEntry = groupValue.get(mq);
                if (null == lockEntry) {
                    lockEntry = new LockEntry();
                    lockEntry.setClientId(clientId);
                    groupValue.put(mq, lockEntry);
                    log.info("tryLock, message queue not locked, I got it. Group: {} NewClientId: {} {}", //
                        group, //
                        clientId, //
                        mq);
                }

                if (lockEntry.isLocked(clientId)) {
                    lockEntry.setLastUpdateTimestamp(System.currentTimeMillis());
                    return true;
                }

                String oldClientId = lockEntry.getClientId();

                // 锁已经过期,抢占它
                if (lockEntry.isExpired()) {
                    lockEntry.setClientId(clientId);
                    lockEntry.setLastUpdateTimestamp(System.currentTimeMillis());
                    log.warn(
                        "tryLock, message queue lock expired, I got it. Group: {} OldClientId: {} NewClientId: {} {}", //
                        group, //
                        oldClientId, //
                        clientId, //
                        mq);
                    return true;
                }

                // 锁被别的Client占用
                log.warn(
                    "tryLock, message queue locked by other client. Group: {} OtherClientId: {} NewClientId: {} {}", //
                    group, //
                    oldClientId, //
                    clientId, //
                    mq);
                return false;
            }
            finally {
                this.lock.unlock();
            }
        }
        catch (InterruptedException e) {
            log.error("putMessage exception", e);
        }
    }
    // 已经锁住,尝试更新时间
    else {
        // isLocked 中已经更新了时间,这里不需要再更新
    }

    return true;
}
 
Example 18
Source File: MetricAssociation.java    From StatsAgg with Apache License 2.0 4 votes vote down vote up
private static Boolean associateMetricKeyWithId(String metricKey, Integer id, 
        ConcurrentHashMap<Integer,Set<String>> matchingMetricKeysAssociatedWithId,
        ConcurrentHashMap<Integer,String> mergedMatchRegexesById,
        ConcurrentHashMap<Integer,String> mergedBlacklistRegexesById) {

    ConcurrentHashMap<String,String> immediateCleanupMetrics = GlobalVariables.immediateCleanupMetrics;
    if ((immediateCleanupMetrics != null) && !immediateCleanupMetrics.isEmpty() && immediateCleanupMetrics.containsKey(metricKey)) return null;
    
    boolean didMatch = false;
    
    try {
        String matchRegex = mergedMatchRegexesById.get(id);
        if (matchRegex == null) return null;

        Pattern matchPattern = getPatternFromRegexString(matchRegex);

        if (matchPattern != null) {
            Matcher matchMatcher = matchPattern.matcher(metricKey);
            boolean isMatchRegexMatch = matchMatcher.matches();
            boolean isMetricKeyAssociatedWithId = false;

            if (isMatchRegexMatch) {
                String blacklistRegex = mergedBlacklistRegexesById.get(id);
                Pattern blacklistPattern = getPatternFromRegexString(blacklistRegex);

                if (blacklistPattern != null) {
                    Matcher blacklistMatcher = blacklistPattern.matcher(metricKey);
                    boolean isBlacklistRegexMatch = blacklistMatcher.matches();
                    if (!isBlacklistRegexMatch) isMetricKeyAssociatedWithId = true;
                }
                else isMetricKeyAssociatedWithId = true;
            }

            if (isMetricKeyAssociatedWithId) {
                Set<String> matchingMetricKeyAssociations = matchingMetricKeysAssociatedWithId.get(id);

                if (matchingMetricKeyAssociations == null) {
                    matchingMetricKeyAssociations = new HashSet<>();
                    matchingMetricKeysAssociatedWithId.put(id, Collections.synchronizedSet(matchingMetricKeyAssociations));
                }

                matchingMetricKeyAssociations.add(metricKey);
            }
            
            didMatch = isMetricKeyAssociatedWithId;
        }
    }
    catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    }
    
    return didMatch;
}
 
Example 19
Source File: Utils.java    From Tangram-Android with MIT License 4 votes vote down vote up
public static <K, V> Map<K, V> newMap(K k1, V v1, K k2, V v2) {
    ConcurrentHashMap<K, V> map = new ConcurrentHashMap<>();
    map.put(k1, v1);
    map.put(k2, v2);
    return map;
}
 
Example 20
Source File: EditDataSet.java    From chart-fx with Apache License 2.0 4 votes vote down vote up
protected void findDataPoint(final Axis xAxis, final Axis yAxis, final List<DataSet> dataSets) {
    if (xAxis == null || yAxis == null || dataSets == null) {
        return;
    }
    final double xMinScreen = Math.min(selectStartPoint.getX(), selectEndPoint.getX());
    final double xMaxScreen = Math.max(selectStartPoint.getX(), selectEndPoint.getX());
    final double yMinScreen = Math.min(selectStartPoint.getY(), selectEndPoint.getY());
    final double yMaxScreen = Math.max(selectStartPoint.getY(), selectEndPoint.getY());

    for (final DataSet ds : dataSets) {
        if (!(ds instanceof EditableDataSet)) {
            continue;
        }
        final EditableDataSet dataSet = (EditableDataSet) ds;

        final int indexMin = Math.max(0, ds.getIndex(DataSet.DIM_X, xAxis.getValueForDisplay(xMinScreen)));
        final int indexMax = Math.min(ds.getIndex(DataSet.DIM_X, xAxis.getValueForDisplay(xMaxScreen)) + 1,
                ds.getDataCount());

        // N.B. (0,0) screen coordinate is in the top left corner vs. normal
        // 0,0 in the bottom left -> need to invert limits
        final double yMax = yAxis.getValueForDisplay(yMinScreen);
        final double yMin = yAxis.getValueForDisplay(yMaxScreen);

        final ConcurrentHashMap<Integer, SelectedDataPoint> dataSetHashMap = markedPoints.computeIfAbsent(dataSet,
                k -> new ConcurrentHashMap<>());
        for (int i = indexMin; i < indexMax; i++) {
            final double y = dataSet.get(DataSet.DIM_Y, i);
            if ((y >= yMin) && (y <= yMax)) {
                if (isShiftDown()) {
                    // add if not existing/remove if existing
                    if (dataSetHashMap.get(i) != null) {
                        dataSetHashMap.remove(i);
                    } else {
                        dataSetHashMap.put(i, new SelectedDataPoint(xAxis, yAxis, dataSet, i));
                    }
                } else {
                    dataSetHashMap.put(i, new SelectedDataPoint(xAxis, yAxis, dataSet, i));
                }
            }
        }
    }
}