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

The following are Jave code examples for showing how to use entrySet() 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: CraftyProfessions   File: BlockTable.java   View Source Code Vote up 7 votes
/** CURRENTLY UNTESTED! NEED TO REPLICATE THIS IN THE READING OF THE FILE AS WELL
 * This method will write the table specified by the internal parents
 * protected mTableName field.
 *
 * @param controller The configuration controller in order to gain
 *                   access to a specified resource file.
 */
@Override
public void writeTable (ConfigController controller)
{
    YamlConfiguration wageTable = controller.getSpecialConfig (mTableName.getFileName ());

    for (Map.Entry<String, ConcurrentHashMap<String, BigDecimal>> tableEntry : mBlockMap.entrySet ())
    {
        ConcurrentHashMap<String, BigDecimal> tableMap = tableEntry.getValue ();
        ConcurrentHashMap<String, BigDecimal> blockMapSection = mBlockMap.get (tableEntry.getKey ());

        for (Map.Entry<String, BigDecimal> entry : tableMap.entrySet ())
        {
            wageTable.set (tableEntry.getKey () + "." + entry.getKey (), blockMapSection.get (entry.getKey ()));
        }
    }

    controller.saveConfig (wageTable, mTableName.getFileName ());
}
 
Example 2
Project: MarsBootProject   File: ParametersCreator.java   View Source Code Vote up 7 votes
/**
 * add requestParams to query parameter for url
 * */
HttpUrl buildQueryParameter() {
    if (requestParams == null) {
        return url;
    }

    final ConcurrentHashMap<String, String> urlParams = requestParams.urlParams;
    HttpUrl.Builder builder = url.newBuilder();
    for (Map.Entry<String, String> entry : urlParams.entrySet()) {
        builder.addQueryParameter(entry.getKey(), entry.getValue());
    }

    url = builder.build();
    return url;

}
 
Example 3
Project: NYBus   File: NYBusDriver.java   View Source Code Vote up 7 votes
/**
 * Is target registered.
 *
 * @param targetObject    the target object.
 * @param targetChannelId the target channel id.
 * @return is target registered.
 */
private boolean isTargetRegistered(Object targetObject, List<String> targetChannelId) {
    Set<String> currentlyRegisteredChannelId = new HashSet<>();
    for (Map.Entry<Class<?>, ConcurrentHashMap<Object, ConcurrentHashMap<String,
            SubscriberHolder>>> mEventsToTargetsMapEntry : mEventsToTargetsMap.entrySet()) {
        ConcurrentHashMap<Object, ConcurrentHashMap<String, SubscriberHolder>> mTargetMap =
                mEventsToTargetsMapEntry.getValue();
        if (mTargetMap.containsKey(targetObject)) {
            ConcurrentHashMap<String, SubscriberHolder> subscribeMethods = mTargetMap.get
                    (targetObject);
            for (Map.Entry<String, SubscriberHolder> subscribeMethodEntry : subscribeMethods.entrySet()) {
                for (String methodChannelID : subscribeMethodEntry.getValue().subscribedChannelID) {
                    currentlyRegisteredChannelId.add(methodChannelID);

                }
            }
        }
    }
    return currentlyRegisteredChannelId.size() > 0 && currentlyRegisteredChannelId.containsAll(targetChannelId);
}
 
Example 4
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 7 votes
/**
 * entrySet contains all pairs
 */
public void testEntrySet() {
    ConcurrentHashMap map = map5();
    Set s = map.entrySet();
    assertEquals(5, s.size());
    Iterator it = s.iterator();
    while (it.hasNext()) {
        Map.Entry e = (Map.Entry) it.next();
        assertTrue(
                   (e.getKey().equals(one) && e.getValue().equals("A")) ||
                   (e.getKey().equals(two) && e.getValue().equals("B")) ||
                   (e.getKey().equals(three) && e.getValue().equals("C")) ||
                   (e.getKey().equals(four) && e.getValue().equals("D")) ||
                   (e.getKey().equals(five) && e.getValue().equals("E")));
    }
}
 
Example 5
Project: openjdk-jdk10   File: DistinctEntrySetElements.java   View Source Code Vote up 7 votes
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 6
Project: monarch   File: AutoSerializableJUnitTest.java   View Source Code Vote up 7 votes
@Override
public Object writeTransform(Field f, Class<?> clazz, Object originalValue) {
  if (f.getType().equals(ConcurrentHashMap.class)) {
    Object[] result = null;
    if (originalValue != null) {
      ConcurrentHashMap<?, ?> m = (ConcurrentHashMap<?, ?>) originalValue;
      result = new Object[m.size() * 2];
      int i = 0;
      for (Map.Entry<?, ?> e : m.entrySet()) {
        result[i++] = e.getKey();
        result[i++] = e.getValue();
      }
    }
    return result;
  } else {
    return super.writeTransform(f, clazz, originalValue);
  }
}
 
Example 7
Project: apache-tomcat-7.0.73-with-comment   File: SlowQueryReportJmx.java   View Source Code Vote up 7 votes
/**
 * JMX operation - returns all the queries we have collected.
 * @return - the slow query report as composite data.
 */
@Override
public CompositeData[] getSlowQueriesCD() throws OpenDataException {
    CompositeDataSupport[] result = null;
    ConcurrentHashMap<String,QueryStats> queries = perPoolStats.get(poolName);
    if (queries!=null) {
        Set<Map.Entry<String,QueryStats>> stats = queries.entrySet();
        if (stats!=null) {
            result = new CompositeDataSupport[stats.size()];
            Iterator<Map.Entry<String,QueryStats>> it = stats.iterator();
            int pos = 0;
            while (it.hasNext()) {
                Map.Entry<String,QueryStats> entry = it.next();
                QueryStats qs = entry.getValue();
                result[pos++] = qs.getCompositeData(getCompositeType());
            }
        }
    }
    return result;
}
 
Example 8
Project: jdk8u-jdk   File: DistinctEntrySetElements.java   View Source Code Vote up 7 votes
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 9
Project: TakinRPC   File: ChannelManager.java   View Source Code Vote up 6 votes
/**
 * 检查 关闭的channel
 * 
 * @param channelMap
 */
private void checkCloseChannel(ConcurrentHashMap<String, List<ChannelWrapper>> channelMap) {
    for (Map.Entry<String, List<ChannelWrapper>> entry : channelMap.entrySet()) {
        List<ChannelWrapper> channels = entry.getValue();
        List<ChannelWrapper> removeList = new ArrayList<ChannelWrapper>();
        for (ChannelWrapper channel : channels) {
            if (channel.isClosed()) {
                removeList.add(channel);
                logger.info(String.format("close channel=%s", channel));
            }
        }
        channels.removeAll(removeList);
    }
}
 
Example 10
Project: ZooKeeper   File: SessionTrackerImpl.java   View Source Code Vote up 6 votes
public SessionTrackerImpl(SessionExpirer expirer,
        ConcurrentHashMap<Long, Integer> sessionsWithTimeout, int tickTime,
        long sid, ZooKeeperServerListener listener)
{
    super("SessionTracker", listener);
    this.expirer = expirer;
    this.expirationInterval = tickTime;
    this.sessionsWithTimeout = sessionsWithTimeout;
    nextExpirationTime = roundToInterval(System.currentTimeMillis());
    this.nextSessionId = initializeNextSession(sid);
    for (Entry<Long, Integer> e : sessionsWithTimeout.entrySet()) {
        addSession(e.getKey(), e.getValue());
    }
}
 
Example 11
Project: fuck_zookeeper   File: SessionTrackerImpl.java   View Source Code Vote up 6 votes
public SessionTrackerImpl(SessionExpirer expirer,
        ConcurrentHashMap<Long, Integer> sessionsWithTimeout, int tickTime,
        long sid, ZooKeeperServerListener listener)
{
    super("SessionTracker", listener);
    this.expirer = expirer;
    this.expirationInterval = tickTime;
    this.sessionsWithTimeout = sessionsWithTimeout;
    nextExpirationTime = roundToInterval(System.currentTimeMillis());
    this.nextSessionId = initializeNextSession(sid);
    for (Entry<Long, Integer> e : sessionsWithTimeout.entrySet()) {
        addSession(e.getKey(), e.getValue());
    }
}
 
Example 12
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 6 votes
/**
 * entrySet.toArray contains all entries
 */
public void testEntrySetToArray() {
    ConcurrentHashMap map = map5();
    Set s = map.entrySet();
    Object[] ar = s.toArray();
    assertEquals(5, ar.length);
    for (int i = 0; i < 5; ++i) {
        assertTrue(map.containsKey(((Map.Entry)(ar[i])).getKey()));
        assertTrue(map.containsValue(((Map.Entry)(ar[i])).getValue()));
    }
}
 
Example 13
Project: fiery   File: APIStatisticTimeSet.java   View Source Code Vote up 6 votes
public TreeMap<Long, APIStatisticStruct> getHourDetail(String url, Long shardtime) {
    TreeMap<Long, APIStatisticStruct> urlStatics = new TreeMap<>();

    if (apiTopHourStaticHelper.containsKey(url)) {
        //return apiTopHourStaticHelper.get(url);
        ConcurrentHashMap<Long, APIStatisticStruct> staticsSet = apiTopHourStaticHelper.get(url);

        for (Map.Entry<Long, APIStatisticStruct> statisticItem : staticsSet.entrySet()) {
            if (statisticItem.getKey() >= shardtime && statisticItem.getKey() <= shardtime + 86400) {
                urlStatics.put(DateTimeHelper.getHour(statisticItem.getKey()), statisticItem.getValue());
            }
        }
    }
    return urlStatics;
}
 
Example 14
Project: metacom-android   File: AndroidJSTPConnection.java   View Source Code Vote up 6 votes
private void sendCachedCalls(final String tag) {
    ConcurrentHashMap<UUID, CacheCallData> cacheCalls = mTaggedCacheCalls.get(tag);
    if (cacheCalls == null) return;

    for (final Map.Entry<UUID, CacheCallData> callData : cacheCalls.entrySet()) {
        sendCachedCall(tag, callData.getKey(), callData.getValue());
    }
}
 
Example 15
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 6 votes
/**
 * hashCode() equals sum of each key.hashCode ^ value.hashCode
 */
public void testHashCode() {
    ConcurrentHashMap<Integer,String> map = map5();
    int sum = 0;
    for (Map.Entry<Integer,String> e : map.entrySet())
        sum += e.getKey().hashCode() ^ e.getValue().hashCode();
    assertEquals(sum, map.hashCode());
}
 
Example 16
Project: monarch   File: DataSerializer.java   View Source Code Vote up 6 votes
/**
 * Writes a <code>ConcurrentHashMap</code> to a <code>DataOutput</code>. Note that even though
 * <code>map</code> may be an instance of a subclass of <code>ConcurrentHashMap</code>,
 * <code>readConcurrentHashMap</code> will always return an instance of
 * <code>ConcurrentHashMap</code>, <B>not</B> an instance of the subclass. To preserve the class
 * type of <code>map</code>, {@link #writeObject(Object, DataOutput)} should be used for data
 * serialization.
 * <P>
 * At this time if {@link #writeObject(Object, DataOutput)} is called with an instance of
 * ConcurrentHashMap then it will be serialized with normal java.io Serialization. So if you want
 * the keys and values of a ConcurrentHashMap to take advantage of GemFire serialization it must
 * be serialized with this method.
 *
 * @throws IOException A problem occurs while writing to <code>out</code>
 *
 * @see #readConcurrentHashMap
 * @since GemFire 6.6
 */
public static void writeConcurrentHashMap(ConcurrentHashMap<?, ?> map, DataOutput out)
    throws IOException {

  InternalDataSerializer.checkOut(out);

  int size;
  Collection<Map.Entry<?, ?>> entrySnapshot = null;
  if (map == null) {
    size = -1;
  } else {
    // take a snapshot to fix bug 44562
    entrySnapshot = new ArrayList<Map.Entry<?, ?>>(map.entrySet());
    size = entrySnapshot.size();
  }
  InternalDataSerializer.writeArrayLength(size, out);
  if (logger.isTraceEnabled(LogMarker.SERIALIZER)) {
    logger.trace(LogMarker.SERIALIZER, "Writing ConcurrentHashMap with {} elements: {}", size,
        entrySnapshot);
  }
  if (size > 0) {
    for (Map.Entry<?, ?> entry : entrySnapshot) {
      writeObject(entry.getKey(), out);
      writeObject(entry.getValue(), out);
    }
  }
}
 
Example 17
Project: apache-tomcat-7.0.73-with-comment   File: StatementCache.java   View Source Code Vote up 6 votes
@Override
public void disconnected(ConnectionPool parent, PooledConnection con, boolean finalizing) {
    @SuppressWarnings("unchecked")
    ConcurrentHashMap<CacheKey,CachedStatement> statements =
        (ConcurrentHashMap<CacheKey,CachedStatement>)con.getAttributes().get(STATEMENT_CACHE_ATTR);

    if (statements!=null) {
        for (Map.Entry<CacheKey, CachedStatement> p : statements.entrySet()) {
            closeStatement(p.getValue());
        }
        statements.clear();
    }

    super.disconnected(parent, con, finalizing);
}
 
Example 18
Project: angel   File: PSManagerTest.java   View Source Code Vote up 5 votes
@Test
public void testPSReport() throws Exception {
  try {
    ParameterServer ps = LocalClusterContext.get().getPS(psAttempt0Id).getPS();
    Location masterLoc = ps.getMasterLocation();
    TConnection connection = TConnectionManager.getConnection(ps.getConf());
    MasterProtocol master = connection.getMasterService(masterLoc.getIp(), masterLoc.getPort());
    PSReportRequest.Builder builder = PSReportRequest.newBuilder();
    builder.setPsAttemptId(ProtobufUtil.convertToIdProto(psAttempt0Id));
    Pair.Builder pairBuilder = Pair.newBuilder();
    pairBuilder.setKey("ps_key1");
    pairBuilder.setValue("100");
    builder.addMetrics(pairBuilder.build());
    pairBuilder.setKey("ps_key2");
    pairBuilder.setValue("200");
    builder.addMetrics(pairBuilder.build());
    builder.setPsFailedReports(MLProtos.PSFailedReportsProto.getDefaultInstance());

    MatrixReportProto.Builder matrixBuilder = MatrixReportProto.newBuilder();
    ConcurrentHashMap<Integer, ServerMatrix> matrixIdMap = ps.getMatrixStorageManager().getMatrices();
    for (Entry<Integer, ServerMatrix> matrixEntry : matrixIdMap.entrySet()) {
      builder.addMatrixReports((matrixBuilder.setMatrixId(matrixEntry.getKey())
        .setMatrixName(matrixEntry.getValue().getName())));
    }

    PSReportResponse response = master.psReport(null, builder.build());
    assertEquals(response.getPsCommand(), PSCommandProto.PSCOMMAND_OK);
    assertEquals(response.getNeedCreateMatricesCount(), 0);
    assertEquals(response.getNeedReleaseMatrixIdsCount(), 0);
    AngelApplicationMaster angelAppMaster = LocalClusterContext.get().getMaster().getAppMaster();
    ParameterServerManager psManager = angelAppMaster.getAppContext().getParameterServerManager();
    AMParameterServer amPs = psManager.getParameterServer(psId);
    PSAttempt psAttempt = amPs.getPSAttempt(psAttempt0Id);
    Map<String, String> metrices = psAttempt.getMetrices();
    assertTrue(metrices.get("ps_key1").equals("100"));
    assertTrue(metrices.get("ps_key2").equals("200"));

    PSAttemptId psAttempt1Id = new PSAttemptId(psId, 1);
    builder.setPsAttemptId(ProtobufUtil.convertToIdProto(psAttempt1Id));
    response = master.psReport(null, builder.build());
    assertEquals(response.getPsCommand(), PSCommandProto.PSCOMMAND_SHUTDOWN);
  } catch (Exception x) {
    LOG.error("run testPSReport failed ", x);
    throw x;
  }
}
 
Example 19
Project: fiery   File: APIStatisticTimeSet.java   View Source Code Vote up 5 votes
@PreDestroy
public void dumpStaticDb() {
    log.info("dump the Statistic info start...");

    //loop day
    for (Map.Entry<Long, ConcurrentHashMap<String, APIStatisticStruct>> ent : apiTopStaticHelper.entrySet()) {
        StringBuilder staticSting = new StringBuilder();
        StringBuilder staticHourString = new StringBuilder();

        Long shardTime = ent.getKey();
        ConcurrentHashMap<String, APIStatisticStruct> apiStatisticStructMap = ent.getValue();

        //fetch all day total statics
        for (Map.Entry<String, APIStatisticStruct> urlShard : apiStatisticStructMap.entrySet()) {
            String jsonStr = urlShard.getValue().toJson();
            if (jsonStr.trim().length() > 0) {
                staticSting.append(jsonStr + "\r\n");
            }

            //store the Hour String
            if (apiTopHourStaticHelper.containsKey(urlShard.getKey())) {
                Long compareEnd = shardTime + 86400;
                //check this url hour map
                for (Map.Entry<Long, APIStatisticStruct> hourStatistic : apiTopHourStaticHelper.get(urlShard.getKey()).entrySet()) {
                    //filter
                    if (hourStatistic.getKey() <= compareEnd && hourStatistic.getKey() >= shardTime) {
                        staticHourString.append(hourStatistic.getValue().toJson() + "\r\n");
                    }
                }
            }
        }

        log.info("dump the Statistic info:" + shardTime + " len:" + apiStatisticStructMap.size());
        log.info("dump the stattistic hour info:" + shardTime +" len:"+ staticHourString.toString().length());

        DBSharder dbSharder = dbManage.getDB(shardTime);

        //day
        if (staticSting.length() > 0 && dbSharder != null) {
            dbSharder.put("apitopstatistic", staticSting.toString());
        }

        //hour
        if (staticHourString.length() > 0 && dbSharder != null) {
            dbSharder.put("apitophourstatistic", staticHourString.toString());
        }
    }

}
 
Example 20
Project: lams   File: JdbcTypeJavaClassMappings.java   View Source Code Vote up 5 votes
private static ConcurrentHashMap<Integer, Class> transpose(ConcurrentHashMap<Class, Integer> javaClassToJdbcTypeCodeMap) {
	final ConcurrentHashMap<Integer, Class> transposed = new ConcurrentHashMap<Integer, Class>();

	for ( Map.Entry<Class,Integer> entry : javaClassToJdbcTypeCodeMap.entrySet() ) {
		transposed.put( entry.getValue(), entry.getKey() );
	}

	return transposed;
}