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

The following examples show how to use java.util.concurrent.ConcurrentMap#keySet() . 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: DefaultOvsdbClient.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public Set<OvsdbBridge> getBridges() {
    Set<OvsdbBridge> ovsdbBridges = new HashSet<>();
    OvsdbTableStore tableStore = getTableStore(DATABASENAME);
    if (tableStore == null) {
        return ovsdbBridges;
    }
    OvsdbRowStore rowStore = tableStore.getRows(BRIDGE);
    if (rowStore == null) {
        return ovsdbBridges;
    }
    ConcurrentMap<String, Row> rows = rowStore.getRowStore();
    for (String uuid : rows.keySet()) {
        Row bridgeRow = getRow(DATABASENAME, BRIDGE, uuid);
        OvsdbBridge ovsdbBridge = getOvsdbBridge(bridgeRow, Uuid.uuid(uuid));
        if (ovsdbBridge != null) {
            ovsdbBridges.add(ovsdbBridge);
        }
    }
    return ovsdbBridges;
}
 
Example 2
Source File: MqttProducerManager.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
public void removeProducer(String clientID) {
    if (connectionManager.isConnected(clientID)) {
        MqttConnection connection = connectionManager.getConnection(clientID);
        ConcurrentMap<String, ConcurrentMap<String, String>> topicProducers = connection.getProducers();
        if (topicProducers != null) {
            for (String topic : topicProducers.keySet()) {
                ConcurrentMap<String, String> applicationProducers = topicProducers.get(topic);
                if (applicationProducers != null) {
                    for (String application : applicationProducers.keySet()) {
                        String producerId = applicationProducers.get(application);
                        if (!Strings.isNullOrEmpty(producerId)) {
                            producers.remove(producerId);
                        }
                    }
                }
            }
        }
    }
}
 
Example 3
Source File: DefaultOvsdbClient.java    From onos with Apache License 2.0 6 votes vote down vote up
private String getOvsUuid(String dbName) {
    OvsdbRowStore rowStore = getRowStore(DATABASENAME, DATABASENAME);
    if (rowStore == null) {
        log.debug("The bridge uuid is null");
        return null;
    }
    ConcurrentMap<String, Row> ovsTableRows = rowStore.getRowStore();
    if (ovsTableRows != null) {
        for (String uuid : ovsTableRows.keySet()) {
            Row row = ovsTableRows.get(uuid);
            String tableName = row.tableName();
            if (tableName.equals(dbName)) {
                return uuid;
            }
        }
    }
    return null;
}
 
Example 4
Source File: DefaultConverter.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
private List<MonitorRecord> buildReceive(String brokerId, long time, BrokerStat brokerStat) {
    List<MonitorRecord> result = new ArrayList<>();

    ConcurrentMap<String, TopicStat> repStats = brokerStat.getTopicStats();
    for (String topic : repStats.keySet()) {
        ConcurrentMap<Integer, PartitionGroupStat> pgStats = repStats.get(topic).getPartitionGroupStatMap();
        for (Integer pg : pgStats.keySet()) {
            result.addAll(buildReceiveRecord(topic, pg, pgStats.get(pg), brokerId, time));
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Receive size : {}", result.size());
    }

    return result;
}
 
Example 5
Source File: ServiceLoader.java    From beihu-boot with Apache License 2.0 5 votes vote down vote up
public static Set<String> getServiceProviders(final Class<?> clazz) {

        if (clazz == null)
            throw new IllegalArgumentException("type == null");
        if (!clazz.isInterface()) {
            throw new IllegalArgumentException(" type(" + clazz + ") is not interface!");
        }
        if (!clazz.isAnnotationPresent(SPI.class)) {
            throw new IllegalArgumentException("type(" + clazz +
                    ") is not extension, because WITHOUT @" + SPI.class.getSimpleName() + " Annotation!");
        }

        SPI spi = clazz.getAnnotation(SPI.class);
        String defaultName = spi.dftValue();
        String dynamicConfigKey = spi.key();


        final Set<URLDefinition> urlDefinitions = new HashSet<URLDefinition>();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        urlDefinitions.addAll(collectExtensionUrls(LTS_DIRECTORY + clazz.getName(), classLoader));
        urlDefinitions.addAll(collectExtensionUrls(LTS_INTERNAL_DIRECTORY + clazz.getName(), classLoader));

        final ConcurrentMap<String, ServiceDefinition> serviceDefinitions = new ConcurrentHashMap<String, ServiceDefinition>();
        for (URLDefinition urlDefinition : urlDefinitions) {
            serviceDefinitions.putAll(parse(urlDefinition));
        }
        if (serviceDefinitions.isEmpty()) {
            throw new IllegalStateException("Service loader could not load " + clazz.getName() + "'s ServiceProvider from '" + LTS_DIRECTORY + "' or '" + LTS_INTERNAL_DIRECTORY + "' It may be empty or does not exist.");
        }
        ServiceProvider serviceProvider = new ServiceProvider(clazz, dynamicConfigKey, defaultName, serviceDefinitions);
        serviceMap.remove(clazz);   // 先移除
        serviceMap.put(clazz, serviceProvider);
        return serviceDefinitions.keySet();
    }
 
Example 6
Source File: AllConnectConnectionHolder.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public List<ProviderInfo> getAvailableProviders() {
    // 存活为空的,那就用亚健康的
    ConcurrentMap<ProviderInfo, ClientTransport> map =
            aliveConnections.isEmpty() ? subHealthConnections : aliveConnections;
    return new ArrayList<ProviderInfo>(map.keySet());
}
 
Example 7
Source File: Issue37Test.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void test2() throws IOException{

    /**
     * Tijdelijke on-disk database gebruiken.
     */
    DB db = DBMaker.newTempFileDB().cacheDisable().make();
    ConcurrentMap<String,String> testData = db.createHashMap("test",
            null, null);

    BufferedReader in = new BufferedReader(new FileReader("./src/test/resources/Issue37Data.txt"));
    String line = null;

    while ((line = in.readLine()) != null){
        testData.put(line,line);
    }

    db.commit();

    int printCount = 0;

    for(String key : testData.keySet()){
        printCount++;

        String data = testData.get(key);

        if(printCount > 10000){
            fail();
        }
    }
}
 
Example 8
Source File: DefaultProcessEngineFactory.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void copyWsConfig(ProcessEngineConfigurationImpl flowable6Configuration, org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl flowable5Configuration) {
    if (flowable6Configuration.getWsSyncFactoryClassName() != null) {
        flowable5Configuration.setWsSyncFactoryClassName(flowable6Configuration.getWsSyncFactoryClassName());
    }

    ConcurrentMap<QName, URL> endpointMap = flowable6Configuration.getWsOverridenEndpointAddresses();
    if (endpointMap != null) {
        for (QName endpointQName : endpointMap.keySet()) {
            flowable5Configuration.addWsEndpointAddress(endpointQName, endpointMap.get(endpointQName));
        }
    }
}
 
Example 9
Source File: WebSocketConnectionRegistry.java    From actframework with Apache License 2.0 5 votes vote down vote up
/**
 * Accept a visitor to iterate through the connections attached to the key specified
 *
 * @param key
 *         the key
 * @param visitor
 *         the visitor
 */
public void accept(String key, $.Function<WebSocketConnection, ?> visitor) {
    ConcurrentMap<WebSocketConnection, WebSocketConnection> connections = registry.get(key);
    if (null == connections) {
        return;
    }
    if (!connections.isEmpty()) {
        lock.lock();
        try {
            List<WebSocketConnection> toBeCleared = null;
            for (WebSocketConnection conn : connections.keySet()) {
                if (conn.closed()) {
                    if (null == toBeCleared) {
                        toBeCleared = new ArrayList<>();
                    }
                    toBeCleared.add(conn);
                    continue;
                }
                visitor.apply(conn);
            }
            if (null != toBeCleared) {
                ConcurrentMap<WebSocketConnection, WebSocketConnection> originalCopy = registry.get(key);
                originalCopy.keySet().removeAll(toBeCleared);
            }
        } finally {
            lock.unlock();
        }
    }
}
 
Example 10
Source File: ServiceDiscovery.java    From mercury with Apache License 2.0 5 votes vote down vote up
public static List<String> getRoutes(String origin) {
    List<String> result = new ArrayList<>();
    if (origin == null) {
        return result;
    }
    ConcurrentMap<String, Boolean> entries = origins.get(origin);
    if (entries != null) {
        for (String r: entries.keySet()) {
            result.add(r);
        }
    }
    return result;
}
 
Example 11
Source File: PullMessageWorker.java    From qmq with Apache License 2.0 5 votes vote down vote up
void remindNewMessages(final String subject) {
    final ConcurrentMap<String, Object> map = this.subscribers.get(subject);
    if (map == null) return;

    for (String group : map.keySet()) {
        map.remove(group);
        this.actorSystem.resume(ConsumerGroupUtils.buildConsumerGroupKey(subject, group));
        QMon.resumeActorCountInc(subject, group);
    }
}
 
Example 12
Source File: RsfBeanContainer.java    From hasor with Apache License 2.0 5 votes vote down vote up
/**根据别名系统获取所有已经注册的服务名称。*/
public List<String> getServiceIDs(String category) {
    ConcurrentMap<String, String> aliasNameMaps = this.aliasNameMap.get(category);
    if (aliasNameMaps == null) {
        return Collections.EMPTY_LIST;
    }
    return new ArrayList<>(aliasNameMaps.keySet());
}
 
Example 13
Source File: ConcurrentHashMapTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
/**
 * keySet returns a Set containing all the keys
 */
public void testKeySet() {
    ConcurrentMap map = map5();
    Set s = map.keySet();
    assertEquals(5, s.size());
    assertTrue(s.contains(one));
    assertTrue(s.contains(two));
    assertTrue(s.contains(three));
    assertTrue(s.contains(four));
    assertTrue(s.contains(five));
}
 
Example 14
Source File: WebSocketConnectionRegistry.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
protected void releaseResources() {
    for (ConcurrentMap<WebSocketConnection, WebSocketConnection> connections : registry.values()) {
        for (WebSocketConnection conn : connections.keySet()) {
            conn.destroy();
        }
    }
    registry.clear();
}
 
Example 15
Source File: OnHeapStoreBulkMethodsTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testBulkComputeFunctionGetsValuesOfEntries() throws Exception {
  @SuppressWarnings("rawtypes")
  Store.Configuration config = mock(Store.Configuration.class);
  when(config.getExpiry()).thenReturn(ExpiryPolicyBuilder.noExpiration());
  when(config.getKeyType()).thenReturn(Number.class);
  when(config.getValueType()).thenReturn(Number.class);
  when(config.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(100, MemoryUnit.KB).build());
  Store.Configuration<Number, Number> configuration = config;

  OnHeapStore<Number, Number> store = new OnHeapStore<>(configuration, SystemTimeSource.INSTANCE, IdentityCopier.identityCopier(), IdentityCopier.identityCopier(),
      new DefaultSizeOfEngine(Long.MAX_VALUE, Long.MAX_VALUE), NullStoreEventDispatcher.<Number, Number>nullStoreEventDispatcher(), new DefaultStatisticsService());
  store.put(1, 2);
  store.put(2, 3);
  store.put(3, 4);

  Map<Number, Store.ValueHolder<Number>> result = store.bulkCompute(new HashSet<Number>(Arrays.asList(1, 2, 3, 4, 5, 6)), entries -> {
    Map<Number, Number> newValues = new HashMap<>();
    for (Map.Entry<? extends Number, ? extends Number> entry : entries) {
      final Number currentValue = entry.getValue();
      if(currentValue == null) {
        if(entry.getKey().equals(4)) {
          newValues.put(entry.getKey(), null);
        } else {
          newValues.put(entry.getKey(), 0);
        }
      } else {
        newValues.put(entry.getKey(), currentValue.intValue() * 2);
      }

    }
    return newValues.entrySet();
  });

  ConcurrentMap<Number, Number> check = new ConcurrentHashMap<>();
  check.put(1, 4);
  check.put(2, 6);
  check.put(3, 8);
  check.put(4, 0);
  check.put(5, 0);
  check.put(6, 0);

  assertThat(result.get(1).get(), Matchers.is(check.get(1)));
  assertThat(result.get(2).get(), Matchers.is(check.get(2)));
  assertThat(result.get(3).get(), Matchers.is(check.get(3)));
  assertThat(result.get(4), nullValue());
  assertThat(result.get(5).get(), Matchers.is(check.get(5)));
  assertThat(result.get(6).get(), Matchers.is(check.get(6)));

  for (Number key : check.keySet()) {
    final Store.ValueHolder<Number> holder = store.get(key);
    if(holder != null) {
      check.remove(key, holder.get());
    }
  }
  assertThat(check.size(), is(1));
  assertThat(check.containsKey(4), is(true));

}
 
Example 16
Source File: DefaultConverter.java    From joyqueue with Apache License 2.0 4 votes vote down vote up
private List<MonitorRecord> buildTopicRecord(BrokerStat brokerStat, String brokerId, long time) {

        List<MonitorRecord> records = new ArrayList<>();
        ConcurrentMap<String, TopicStat> topics = brokerStat.getTopicStats();

        for (String tsKey : topics.keySet()) {
            MonitorRecord enQueue = new MonitorRecord();
            fillRecord(enQueue, time);
            enQueue.brokerId(brokerId);

            enQueue.topic(tsKey);

            String[] enQueueMetrics = {TOPIC_SLICE_ENQUEUE, TOPIC_SLICE_ENQUEUE_SIZE,
                    TOPIC_SLICE_ENQUEUE_MAX, TOPIC_SLICE_ENQUEUE_AVG,
                    TOPIC_SLICE_ENQUEUE_MIN, TOPIC_SLICE_ENQUEUE_TP99,
                    TOPIC_SLICE_ENQUEUE_TP90};

            List<MonitorRecord> enQueueRecords = buildEmptyRecords(enQueue, enQueueMetrics);

            if (enQueueRecords != null && enQueueRecords.size() == enQueueMetrics.length) {
                enQueueRecords.get(0).setValue(topics.get(tsKey).getEnQueueStat().getOneMinuteRate());
                enQueueRecords.get(1).setValue(topics.get(tsKey).getEnQueueStat().getSize());
                enQueueRecords.get(2).setValue(topics.get(tsKey).getEnQueueStat().getMax());
                enQueueRecords.get(3).setValue(topics.get(tsKey).getEnQueueStat().getAvg());
                enQueueRecords.get(4).setValue(topics.get(tsKey).getEnQueueStat().getMin());
                enQueueRecords.get(5).setValue(topics.get(tsKey).getEnQueueStat().getTp99());
                enQueueRecords.get(6).setValue(topics.get(tsKey).getEnQueueStat().getTp90());
                records.addAll(enQueueRecords);
            }

            String[] deQueueMetrics = {TOPIC_SLICE_DEQUEUE, TOPIC_SLICE_DEQUEUE_SIZE,
                    TOPIC_SLICE_DEQUEUE_MAX, TOPIC_SLICE_DEQUEUE_AVG,
                    TOPIC_SLICE_DEQUEUE_MIN, TOPIC_SLICE_DEQUEUE_TP99,
                    TOPIC_SLICE_DEQUEUE_TP90};
            List<MonitorRecord> deQueueRecords = buildEmptyRecords(enQueue, deQueueMetrics);

            if (deQueueRecords != null && deQueueRecords.size() == deQueueMetrics.length) {
                deQueueRecords.get(0).setValue(topics.get(tsKey).getDeQueueStat().getOneMinuteRate());
                deQueueRecords.get(1).setValue(topics.get(tsKey).getDeQueueStat().getSize());
                deQueueRecords.get(2).setValue(topics.get(tsKey).getDeQueueStat().getMax());
                deQueueRecords.get(3).setValue(topics.get(tsKey).getDeQueueStat().getAvg());
                deQueueRecords.get(4).setValue(topics.get(tsKey).getDeQueueStat().getMin());
                deQueueRecords.get(5).setValue(topics.get(tsKey).getDeQueueStat().getTp99());
                deQueueRecords.get(6).setValue(topics.get(tsKey).getDeQueueStat().getTp90());
                records.addAll(deQueueRecords);
            }

            // topic storage size monitor record
            String[] topicStorageMetric = {TOPIC_SLICE_STORAGE_SIZE};
            List<MonitorRecord> topicStorageRecords = buildEmptyRecords(enQueue, topicStorageMetric);
            if (topicStorageRecords != null && topicStorageRecords.size() > 0) {
                topicStorageRecords.get(0).setValue(topics.get(tsKey).getStoreSize());
                records.addAll(topicStorageRecords);
            }


        }
        return records;
    }
 
Example 17
Source File: OnHeapStoreBulkMethodsTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testBulkComputeFunctionGetsValuesOfEntries() throws Exception {
  @SuppressWarnings("rawtypes")
  Store.Configuration config = mock(Store.Configuration.class);
  when(config.getExpiry()).thenReturn(ExpiryPolicyBuilder.noExpiration());
  when(config.getKeyType()).thenReturn(Number.class);
  when(config.getValueType()).thenReturn(Number.class);
  when(config.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(Long.MAX_VALUE, EntryUnit.ENTRIES).build());

  OnHeapStore<Number, Number> store = new OnHeapStore<>(config, SystemTimeSource.INSTANCE, IdentityCopier.identityCopier(), IdentityCopier.identityCopier(),
      new NoopSizeOfEngine(), NullStoreEventDispatcher.nullStoreEventDispatcher(), new DefaultStatisticsService());
  store.put(1, 2);
  store.put(2, 3);
  store.put(3, 4);

  Map<Number, Store.ValueHolder<Number>> result = store.bulkCompute(new HashSet<Number>(Arrays.asList(1, 2, 3, 4, 5, 6)), entries -> {
    Map<Number, Number> newValues = new HashMap<>();
    for (Map.Entry<? extends Number, ? extends Number> entry : entries) {
      final Number currentValue = entry.getValue();
      if(currentValue == null) {
        if(entry.getKey().equals(4)) {
          newValues.put(entry.getKey(), null);
        } else {
          newValues.put(entry.getKey(), 0);
        }
      } else {
        newValues.put(entry.getKey(), currentValue.intValue() * 2);
      }

    }
    return newValues.entrySet();
  });

  ConcurrentMap<Number, Number> check = new ConcurrentHashMap<>();
  check.put(1, 4);
  check.put(2, 6);
  check.put(3, 8);
  check.put(4, 0);
  check.put(5, 0);
  check.put(6, 0);

  assertThat(result.get(1).get(), Matchers.is(check.get(1)));
  assertThat(result.get(2).get(), Matchers.is(check.get(2)));
  assertThat(result.get(3).get(), Matchers.is(check.get(3)));
  assertThat(result.get(4), nullValue());
  assertThat(result.get(5).get(), Matchers.is(check.get(5)));
  assertThat(result.get(6).get(), Matchers.is(check.get(6)));

  for (Number key : check.keySet()) {
    final Store.ValueHolder<Number> holder = store.get(key);
    if(holder != null) {
      check.remove(key, holder.get());
    }
  }
  assertThat(check.size(), is(1));
  assertThat(check.containsKey(4), is(true));

}
 
Example 18
Source File: CaffeineCache.java    From t-io with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<String> keys() {
	ConcurrentMap<String, Serializable> map = loadingCache.asMap();
	return map.keySet();
}
 
Example 19
Source File: InfluxDBMapper.java    From influxdb-java with MIT License 4 votes vote down vote up
public <T> void save(final T model) {
  throwExceptionIfMissingAnnotation(model.getClass());
  cacheMeasurementClass(model.getClass());

  ConcurrentMap<String, Field> colNameAndFieldMap = getColNameAndFieldMap(model.getClass());

  try {
    Class<?> modelType = model.getClass();
    String measurement = getMeasurementName(modelType);
    String database = getDatabaseName(modelType);
    String retentionPolicy = getRetentionPolicy(modelType);
    TimeUnit timeUnit = getTimeUnit(modelType);
    long time = timeUnit.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    Point.Builder pointBuilder = Point.measurement(measurement).time(time, timeUnit);

    for (String key : colNameAndFieldMap.keySet()) {
      Field field = colNameAndFieldMap.get(key);
      Column column = field.getAnnotation(Column.class);
      String columnName = column.name();
      Class<?> fieldType = field.getType();

      if (!field.isAccessible()) {
        field.setAccessible(true);
      }

      Object value = field.get(model);

      if (column.tag()) {
        /** Tags are strings either way. */
        pointBuilder.tag(columnName, value.toString());
      } else if ("time".equals(columnName)) {
        if (value != null) {
          setTime(pointBuilder, fieldType, timeUnit, value);
        }
      } else {
        setField(pointBuilder, fieldType, columnName, value);
      }
    }

    Point point = pointBuilder.build();

    if ("[unassigned]".equals(database)) {
      influxDB.write(point);
    } else {
      influxDB.write(database, retentionPolicy, point);
    }

  } catch (IllegalAccessException e) {
    throw new InfluxDBMapperException(e);
  }
}
 
Example 20
Source File: DefaultCommitExecutor.java    From heisenberg with Apache License 2.0 4 votes vote down vote up
/**
 * 提交事务
 */
public void commit(final OkPacket packet, final BlockingSession session, final int initCount) {
    // 初始化
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        this.isFail.set(false);
        this.nodeCount = initCount;
        this.indicatedOK = packet;
    } finally {
        lock.unlock();
    }

    if (session.getSource().isClosed()) {
        decrementCountToZero();
        return;
    }

    // 执行
    final ConcurrentMap<RouteResultsetNode, Channel> target = session.getTarget();
    Executor executor = session.getSource().getProcessor().getExecutor();
    int started = 0;
    for (RouteResultsetNode rrn : target.keySet()) {
        if (rrn == null) {
            try {
                getLogger().error(
                        "null is contained in RoutResultsetNodes, source = " + session.getSource()
                                + ", bindChannel = " + target);
            } catch (Exception e) {
            }
            continue;
        }
        final MySQLChannel mc = (MySQLChannel) target.get(rrn);
        if (mc != null) {
            mc.setRunning(true);
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    _commit(mc, session);
                }
            });
            ++started;
        }
    }

    if (started < initCount && decrementCountBy(initCount - started)) {
        /**
         * assumption: only caused by front-end connection close. <br/>
         * Otherwise, packet must be returned to front-end
         */
        session.clear();
    }
}