Java Code Examples for java.util.concurrent.ConcurrentMap#containsKey()

The following examples show how to use java.util.concurrent.ConcurrentMap#containsKey() . 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: ServiceRegistry.java    From mercury with Apache License 2.0 6 votes vote down vote up
private void removeRoute(String origin, String route) {
    boolean deleted = false;
    if (routes.containsKey(route)) {
        ConcurrentMap<String, String> originMap = routes.get(route);
        if (originMap.containsKey(origin)) {
            originMap.remove(origin);
            deleted = true;
        }
        if (originMap.isEmpty()) {
            routes.remove(route);
        }
    }
    if (deleted) {
        log.info("{} {} unregistered", route, origin);
    }
}
 
Example 2
Source File: QuicksqlServerMeta.java    From Quicksql with MIT License 6 votes vote down vote up
@Override
public void openConnection(ConnectionHandle ch,
    Map<String, String> info) {
    Properties fullInfo = new Properties();
    fullInfo.putAll(this.info);
    if (info != null) {
        fullInfo.putAll(info);
    }

    final ConcurrentMap<String, Connection> cacheAsMap = connectionCache.asMap();
    if (cacheAsMap.containsKey(ch.id)) {
        throw new RuntimeException("Connection already exists: " + ch.id);
    }
    // Avoid global synchronization of connection opening
    try {
        Connection conn = createConnection(url, fullInfo);
        Connection loadedConn = cacheAsMap.putIfAbsent(ch.id, conn);
        // Race condition: someone beat us to storing the connection in the cache.
        if (loadedConn != null) {
            conn.close();
            throw new RuntimeException("Connection already exists: " + ch.id);
        }
    } catch (SQLException e) {
        throw propagate(e);
    }
}
 
Example 3
Source File: FxSingleDeserializer.java    From Strata with Apache License 2.0 6 votes vote down vote up
@Override
public Object build(Class<?> beanType, BeanBuilder<?> builder) {
  BufferingBeanBuilder<?> bld = (BufferingBeanBuilder<?>) builder;
  ConcurrentMap<MetaProperty<?>, Object> buffer = bld.getBuffer();
  BusinessDayAdjustment bda = (BusinessDayAdjustment) buffer.getOrDefault(PAYMENT_ADJUSTMENT_DATE, null);
  if (buffer.containsKey(BASE_CURRENCY_AMOUNT) &&
      buffer.containsKey(COUNTER_CURRENCY_AMOUNT) &&
      buffer.containsKey(PAYMENT_DATE)) {

    CurrencyAmount baseAmount = (CurrencyAmount) builder.get(BASE_CURRENCY_AMOUNT);
    CurrencyAmount counterAmount = (CurrencyAmount) builder.get(COUNTER_CURRENCY_AMOUNT);
    LocalDate paymentDate = (LocalDate) builder.get(PAYMENT_DATE);
    return bda != null ?
        FxSingle.of(baseAmount, counterAmount, paymentDate, bda) :
        FxSingle.of(baseAmount, counterAmount, paymentDate);

  } else {
    Payment basePayment = (Payment) buffer.get(BASE_CURRENCY_PAYMENT);
    Payment counterPayment = (Payment) buffer.get(COUNTER_CURRENCY_PAYMENT);
    return bda != null ? FxSingle.of(basePayment, counterPayment, bda) : FxSingle.of(basePayment, counterPayment);
  }
}
 
Example 4
Source File: MapBasedDeviceConnectionService.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public final Future<DeviceConnectionResult> setCommandHandlingAdapterInstance(final String tenantId,
        final String deviceId, final String protocolAdapterInstanceId, final Duration lifespan, final Span span) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(protocolAdapterInstanceId);

    final ConcurrentMap<String, ExpiringValue<JsonObject>> adapterInstancesForTenantMap = commandHandlingAdapterInstancesMap.computeIfAbsent(tenantId,
            k -> buildAdapterInstancesForTenantMap());
    final DeviceConnectionResult result;
    final int currentMapSize = adapterInstancesForTenantMap.size();
    if (currentMapSize < getConfig().getMaxDevicesPerTenant()
            || (currentMapSize == getConfig().getMaxDevicesPerTenant() && adapterInstancesForTenantMap.containsKey(deviceId))) {
        adapterInstancesForTenantMap.put(deviceId,
                new ExpiringValue<>(createAdapterInstanceIdJson(protocolAdapterInstanceId), getLifespanNanos(lifespan)));
        result = DeviceConnectionResult.from(HttpURLConnection.HTTP_NO_CONTENT);
    } else {
        log.debug("cannot set protocol adapter instance for handling commands of device [{}], tenant [{}]: max number of entries per tenant reached ({})",
                deviceId, tenantId, getConfig().getMaxDevicesPerTenant());
        result = DeviceConnectionResult.from(HttpURLConnection.HTTP_FORBIDDEN);
    }
    return Future.succeededFuture(result);
}
 
Example 5
Source File: ServiceRegistry.java    From mercury with Apache License 2.0 6 votes vote down vote up
private void sendMyRoutes(String origin) throws IOException {
    PostOffice po = PostOffice.getInstance();
    String myOrigin = Platform.getInstance().getOrigin();
    for (String r : routes.keySet()) {
        ConcurrentMap<String, String> originMap = routes.get(r);
        if (originMap.containsKey(myOrigin)) {
            String personality = originMap.get(myOrigin);
            EventEnvelope request = new EventEnvelope();
            request.setTo(ServiceDiscovery.SERVICE_REGISTRY + "@" + origin)
                    .setHeader(TYPE, ADD)
                    .setHeader(ORIGIN, myOrigin)
                    .setHeader(ROUTE, r).setHeader(PERSONALITY, personality);
            po.send(request);
        }
    }
}
 
Example 6
Source File: ConsumerManager.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public HashSet<String> queryTopicConsumeByWho(final String topic) {
    HashSet<String> groups = new HashSet<>();
    Iterator<Entry<String, ConsumerGroupInfo>> it = this.consumerTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, ConsumerGroupInfo> entry = it.next();
        ConcurrentMap<String, SubscriptionData> subscriptionTable =
            entry.getValue().getSubscriptionTable();
        if (subscriptionTable.containsKey(topic)) {
            groups.add(entry.getKey());
        }
    }
    return groups;
}
 
Example 7
Source File: PartitionParser.java    From siddhi with Apache License 2.0 5 votes vote down vote up
private static void validateStreamPartitions(Map<String, PartitionType> partitionTypeMap,
                                             ConcurrentMap<String, AbstractDefinition> streamDefinitionMap,
                                             ConcurrentMap<String, AbstractDefinition> windowDefinitionMap) {
    for (Map.Entry<String, PartitionType> entry : partitionTypeMap.entrySet()) {
        if ((!streamDefinitionMap.containsKey(entry.getKey())) &&
                (!windowDefinitionMap.containsKey(entry.getKey()))) {
            throw new SiddhiAppCreationException("Stream/window with name '" + entry.getKey() +
                    "' is not defined!",
                    entry.getValue().getQueryContextStartIndex(),
                    entry.getValue().getQueryContextEndIndex());
        }
    }
}
 
Example 8
Source File: ClientPool.java    From xio with Apache License 2.0 5 votes vote down vote up
public void release(Client client) {
  log.debug("recycling client {}", client);
  client.recycle();
  ConcurrentMap<Client, Meta> pool = getPool(client.remoteAddress());
  if (pool.size() < maxSizePerAddress && !pool.containsKey(client)) {
    log.debug("releasing client to pool {}", client);
    pool.put(client, new Meta(client));
  } else {
    Meta meta = pool.get(client);
    if (meta != null) {
      log.debug("setting client available in pool {}", client);
      meta.available.set(true);
    }
  }
}
 
Example 9
Source File: ServiceRegistry.java    From mercury with Apache License 2.0 5 votes vote down vote up
private void addRoute(String origin, String route, String personality) {
    if (!routes.containsKey(route)) {
        routes.put(route, new ConcurrentHashMap<>());
    }
    ConcurrentMap<String, String> originMap = routes.get(route);
    if (!originMap.containsKey(origin)) {
        originMap.put(origin, personality);
        origins.put(origin, Utility.getInstance().date2str(new Date(), true));
        log.info("{} {}.{} registered", route, personality, origin);
    }
}
 
Example 10
Source File: FileBasedRegistrationService.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Generate a random device ID.
 */
private String generateDeviceId(final String tenantId) {

    final ConcurrentMap<String, Versioned<Device>> devices = getDevicesForTenant(tenantId);
    String tempDeviceId;
    do {
        tempDeviceId = UUID.randomUUID().toString();
    } while (devices.containsKey(tempDeviceId));
    return tempDeviceId;
}
 
Example 11
Source File: MultiDataCenterEvaluatorToPartitionStrategy.java    From reef with Apache License 2.0 5 votes vote down vote up
private void addLocationMapping(final ConcurrentMap<String,
    BlockingQueue<NumberedSplit<InputSplit>>> concurrentMap,
    final NumberedSplit<InputSplit> numberedSplit, final String location) {
  if (!concurrentMap.containsKey(location)) {
    final BlockingQueue<NumberedSplit<InputSplit>> newSplitQueue = new LinkedBlockingQueue<>();
    concurrentMap.put(location, newSplitQueue);
  }
  concurrentMap.get(location).add(numberedSplit);
}
 
Example 12
Source File: ServiceRegistry.java    From mercury with Apache License 2.0 5 votes vote down vote up
private void addRoute(String origin, String route, String personality) {
    if (!routes.containsKey(route)) {
        routes.put(route, new ConcurrentHashMap<>());
    }
    ConcurrentMap<String, String> originMap = routes.get(route);
    if (!originMap.containsKey(origin)) {
        originMap.put(origin, personality);
        origins.put(origin, Utility.getInstance().date2str(new Date(), true));
        log.info("{} {}.{} registered", route, personality, origin);
    }
}
 
Example 13
Source File: DefaultTransportAttribute.java    From journalkeeper with Apache License 2.0 5 votes vote down vote up
@Override
public boolean contains(Object key) {
    ConcurrentMap<Object, Object> attributes = this.attributes.get();
    if (attributes == null) {
        return false;
    }
    return attributes.containsKey(key);
}
 
Example 14
Source File: ExtensionLoader.java    From pampas with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private ConcurrentMap<String, Class<T>> loadClass(List<String> classNames) {
    ConcurrentMap<String, Class<T>> map = new ConcurrentHashMap<String, Class<T>>();

    for (String className : classNames) {
        try {
            Class<T> clz;
            if (classLoader == null) {
                clz = (Class<T>) Class.forName(className);
            } else {
                clz = (Class<T>) Class.forName(className, true, classLoader);
            }

            checkExtensionType(clz);

            String spiName = getSpiName(clz);

            if (map.containsKey(spiName)) {
                failThrows(clz, ":Error spiName already exist " + spiName);
            } else {
                map.put(spiName, clz);
            }
        } catch (Exception e) {
            failLog(type, "Error load spi class", e);
        }
    }

    return map;

}
 
Example 15
Source File: ConcurrentHashMapTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
/**
 * containsKey(null) throws NPE
 */
public void testContainsKey_NullPointerException() {
    ConcurrentMap c = map();
    try {
        c.containsKey(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 16
Source File: PrometheusMetric.java    From athenz with Apache License 2.0 5 votes vote down vote up
/**
 * Create collector and register it to the registry.
 * This is needed since Athenz metric names are defined on runtime and we need the same collector object to record the data.
 * @param metricName Name of the metric
 * @param builder Prometheus Collector Builder
 */
private Collector createOrGetCollector(String metricName, SimpleCollector.Builder<?, ?> builder) {
    String key = metricName;
    ConcurrentMap<String, Collector> map = this.namesToCollectors;
    Collector collector = map.get(key);

    // double checked locking
    if (collector == null) {
        synchronized (map) {
            if (!map.containsKey(key)) {
                // create
                builder = builder
                    .namespace(this.namespace)
                    .name(metricName)
                    .help(metricName)
                    .labelNames(REQUEST_DOMAIN_LABEL_NAME, PRINCIPAL_DOMAIN_LABEL_NAME);
                collector = builder.register(this.registry);
                // put
                map.put(key, collector);
            } else {
                // get
                collector = map.get(key);
            }
        }
    };

    return collector;
}
 
Example 17
Source File: StateModelFactory.java    From helix with Apache License 2.0 5 votes vote down vote up
/**
 * NOTE: This method is deprecated. Bring it back to keep backward compatible.
 * Replaced by StateModelFactory#removeStateModel(String resourceName, String partitionKey)
 * remove state model for a partition
 * @param partitionName
 * @return state model removed or null if not exist
 */
@Deprecated
public T removeStateModel(String partitionName) {
  // remove the first state model that match partitionName
  // assuming partitionName is unique across all resources
  for (ConcurrentMap<String, T> map : _stateModelMap.values()) {
    if (map.containsKey(partitionName)) {
      return map.remove(partitionName);
    }
  }
  return null;
}
 
Example 18
Source File: RemoteFetchProcessor.java    From rubix with Apache License 2.0 5 votes vote down vote up
protected ConcurrentMap<String, DownloadRequestContext> mergeRequests(long currentTime)
{
  // Till the queue is not empty or there are no more requests which came in before the configured delay time
  // we are going to collect the requests and process them
  ConcurrentMap<String, DownloadRequestContext> contextMap = new ConcurrentHashMap<String, DownloadRequestContext>();
  while (!processQueue.isEmpty()) {
    FetchRequest request = processQueue.peek();
    if (currentTime - request.getRequestedTime() < this.requestProcessDelay) {
      break;
    }

    DownloadRequestContext context = new DownloadRequestContext(request.getRemotePath(), request.getFileSize(),
        request.getLastModified());
    if (!contextMap.containsKey(request.getRemotePath())) {
      contextMap.putIfAbsent(request.getRemotePath(), context);
    }
    else {
      // This takes care of the case where the last modfied time of a file in the request is not matching
      // with the same of other requests. We will take the latest modified time as a source of truth.
      // If the last modfied time in context is less than that of current request, we will remove it from the map
      // Else we will ignore this request.
      if (contextMap.get(request.getRemotePath()).getLastModifiedTime() < request.getLastModified()) {
        contextMap.remove(request.getRemotePath());
        contextMap.putIfAbsent(request.getRemotePath(), context);
      }
      else if (contextMap.get(request.getRemotePath()).getLastModifiedTime() > request.getLastModified()) {
        // TODO add metric to track ignored requests
        processQueue.remove();
        continue;
      }
    }
    contextMap.get(request.getRemotePath()).addDownloadRange(request.getOffset(),
        request.getOffset() + request.getLength());
    processQueue.remove();
    processedRequests.inc();
  }

  return contextMap;
}
 
Example 19
Source File: ConsumerManager.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public HashSet<String> queryTopicConsumeByWho(final String topic) {
    HashSet<String> groups = new HashSet<>();
    Iterator<Entry<String, ConsumerGroupInfo>> it = this.consumerTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, ConsumerGroupInfo> entry = it.next();
        ConcurrentMap<String, SubscriptionData> subscriptionTable =
            entry.getValue().getSubscriptionTable();
        if (subscriptionTable.containsKey(topic)) {
            groups.add(entry.getKey());
        }
    }
    return groups;
}
 
Example 20
Source File: DemoTester.java    From message-queue-java with MIT License 4 votes vote down vote up
public static void main(String args[]) throws Exception {
    //评测相关配置
    //发送阶段的发送数量,也即发送阶段必须要在规定时间内把这些消息发送完毕方可
    int msgNum = 10000000;
    //发送阶段的最大持续时间,也即在该时间内,如果消息依然没有发送完毕,则退出评测
    int sendTime = 2000 * 1000;
    //消费阶段的最大持续时间,也即在该时间内,如果消息依然没有消费完毕,则退出评测
    int checkTime = 1600 * 1000;
    //队列的数量
    int queueNum = 1000000; // attention: currently need to be exact 1000000
    //正确性检测的次数
    int checkNum = queueNum;
    //消费阶段的总队列数量
    int checkQueueNum = queueNum / 10;
    //发送的线程数量
    int sendTsNum = 10;
    //消费的线程数量
    int checkTsNum = 10;        // attention: currently should be exact 10, for the synchronization purpose

    ConcurrentMap<String, AtomicInteger> queueNumMap = new ConcurrentHashMap<>();
    for (int i = 0; i < queueNum; i++) {
        queueNumMap.put("Queue-" + i, new AtomicInteger(0));
    }

    QueueStore queueStore = null;

    try {
        Class queueStoreClass = Class.forName("io.openmessaging.DefaultQueueStoreImpl");
        queueStore = (QueueStore) queueStoreClass.newInstance();
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(-1);
    }

    //Step1: 发送消息
    long sendStart = System.currentTimeMillis();
    long maxTimeStamp = System.currentTimeMillis() + sendTime;
    AtomicLong sendCounter = new AtomicLong(0);
    Thread[] sends = new Thread[sendTsNum];
    for (int i = 0; i < sendTsNum; i++) {
        sends[i] = new Thread(new Producer(queueStore, i, maxTimeStamp, msgNum, sendCounter, queueNumMap));
    }
    for (int i = 0; i < sendTsNum; i++) {
        sends[i].start();
    }
    for (int i = 0; i < sendTsNum; i++) {
        sends[i].join();
    }
    long sendSend = System.currentTimeMillis();
    System.out.printf("Send: %d ms Num:%d\n", sendSend - sendStart, sendCounter.get());
    long maxCheckTime = System.currentTimeMillis() + checkTime;

    //Step2: 索引的正确性校验
    long indexCheckStart = System.currentTimeMillis();
    AtomicLong indexCheckCounter = new AtomicLong(0);
    Thread[] indexChecks = new Thread[checkTsNum];
    for (int i = 0; i < sendTsNum; i++) {
        indexChecks[i] = new Thread(new IndexChecker(queueStore, i, maxCheckTime, checkNum, indexCheckCounter, queueNumMap));
    }
    for (int i = 0; i < sendTsNum; i++) {
        indexChecks[i].start();
    }
    for (int i = 0; i < sendTsNum; i++) {
        indexChecks[i].join();
    }
    long indexCheckEnd = System.currentTimeMillis();
    System.out.printf("Index Check: %d ms Num:%d\n", indexCheckEnd - indexCheckStart, indexCheckCounter.get());

    //Step3: 消费消息,并验证顺序性
    long checkStart = System.currentTimeMillis();
    Random random = new Random();
    AtomicLong checkCounter = new AtomicLong(0);
    Thread[] checks = new Thread[checkTsNum];
    for (int i = 0; i < sendTsNum; i++) {
        int eachCheckQueueNum = checkQueueNum / checkTsNum;
        ConcurrentMap<String, AtomicInteger> offsets = new ConcurrentHashMap<>();
        for (int j = 0; j < eachCheckQueueNum; j++) {
            String queueName = "Queue-" + random.nextInt(queueNum);
            while (offsets.containsKey(queueName)) {
                queueName = "Queue-" + random.nextInt(queueNum);
            }
            offsets.put(queueName, queueNumMap.get(queueName));
        }
        checks[i] = new Thread(new Consumer(queueStore, i, maxCheckTime, checkCounter, offsets));
    }
    for (int i = 0; i < sendTsNum; i++) {
        checks[i].start();
    }
    for (int i = 0; i < sendTsNum; i++) {
        checks[i].join();
    }
    long checkEnd = System.currentTimeMillis();
    System.out.printf("Check: %d ms Num: %d\n", checkEnd - checkStart, checkCounter.get());

    //评测结果
    System.out.printf("Tps:%f\n", ((sendCounter.get() + checkCounter.get() + indexCheckCounter.get()) + 0.1) * 1000 / ((sendSend - sendStart) + (checkEnd - checkStart) + (indexCheckEnd - indexCheckStart)));
}