下面列出了java.util.concurrent.ConcurrentHashMap#entrySet ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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.");
}
}
@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);
}
}
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.");
}
}
/**
* 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 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 (DEBUG) {
InternalDataSerializer.logger.info( LocalizedStrings.DEBUG, "Writing ConcurrentHashMap with " + size + " elements: " + entrySnapshot);
}
if (size > 0) {
for (Map.Entry<?,?> entry: entrySnapshot) {
writeObject(entry.getKey(), out);
writeObject(entry.getValue(), out);
}
}
}
/**
* 重设降级点返回值
*
* @param strategyMap
*/
public void reset(ConcurrentHashMap<String, SdsStrategy> strategyMap) {
ConcurrentHashMap<String, ReturnValue> newMap = new ConcurrentHashMap<>();
if (strategyMap == null || strategyMap.isEmpty()) {
this.pointDowngradeReturnValue = newMap;
return;
}
for (Map.Entry<String, SdsStrategy> stringSdsStrategyEntry : strategyMap.entrySet()) {
newMap.put(stringSdsStrategyEntry.getKey(),
new ReturnValue(stringSdsStrategyEntry.getKey(), stringSdsStrategyEntry.getValue().
getReturnValueStr(), null));
}
this.pointDowngradeReturnValue = newMap;
}
/**
* Remove method from methods map.
*
* @param mTargetMap the target map.
* @param targetObject the target object.
* @param targetChannelId the target channel ids.
*/
private void removeMethodFromMethodsMap(ConcurrentHashMap<Object,
ConcurrentHashMap<String, SubscriberHolder>> mTargetMap,
Object targetObject,
List<String> targetChannelId) {
ConcurrentHashMap<String, SubscriberHolder> mSubscribedMethodsMap =
mTargetMap.get(targetObject);
for (Map.Entry<String, SubscriberHolder> mSubscribedMethodsMapEntry :
mSubscribedMethodsMap.entrySet()) {
SubscriberHolder subscribedMethod = mSubscribedMethodsMapEntry.getValue();
List<String> methodChannelId = subscribedMethod.subscribedChannelID;
if (targetChannelId.containsAll(methodChannelId)) {
mSubscribedMethodsMap.remove(mSubscribedMethodsMapEntry.getKey());
removeTargetIfRequired(mSubscribedMethodsMap, mTargetMap, targetObject);
}
}
}
/**
* 刷出所有的日志统计信息。
*/
protected void flushAll() {
final long flushMillis = System.currentTimeMillis();
// 清理已经回收的对象
expungeLogRef();
// XXX: 输出的日志按 Key 进行排序 -- 先取消
// TreeMap<LogKey, Reference<LogCounter>> map = new TreeMap<LogKey,
// SoftReference<LogCounter>>(map);
ConcurrentHashMap<LogKey, Reference<LogCounter>> map = this.map;
int count = 0;
for (Entry<LogKey, Reference<LogCounter>> entry : map.entrySet()) {
LogCounter counter = entry.getValue().get();
if (counter != null && counter.getCount() > 0) {
LogKey logKey = entry.getKey();
nestLog.write(logKey.getKeys(), counter.getFields(), counter.getValues());
counter.clear();
count++;
}
}
if (count > 0 && logger.isDebugEnabled()) {
logger.debug("flushAll: " + count + " logs in " + (System.currentTimeMillis() - flushMillis)
+ " milliseconds.");
}
}
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.");
}
}
private String takeScreenshot(ITestResult result, String msg) {
String screenId = "";
ConcurrentHashMap<String, CarinaDriver> drivers = getDrivers();
try {
for (Map.Entry<String, CarinaDriver> entry : drivers.entrySet()) {
String driverName = entry.getKey();
WebDriver drv = entry.getValue().getDriver();
if (drv instanceof EventFiringWebDriver) {
drv = ((EventFiringWebDriver) drv).getWrappedDriver();
}
if (Screenshot.isEnabled()) {
screenId = Screenshot.capture(drv, driverName + ": " + msg, true); // in case of failure
}
}
} catch (Throwable thr) {
LOGGER.error("Failure detected on screenshot generation after failure: ", thr);
}
return screenId;
}
private void checkSnapshot() {
for (Entry<String, ConcurrentHashMap<String, CacheData>> cacheDatasEntry : cache.entrySet()) {
ConcurrentHashMap<String, CacheData> cacheDatas = cacheDatasEntry.getValue();
if (null == cacheDatas) {
continue;
}
for (Entry<String, CacheData> cacheDataEntry : cacheDatas.entrySet()) {
final CacheData cacheData = cacheDataEntry.getValue();
// 没有获取本地配置,也没有从diamond server获取配置成功,则加载上一次的snapshot
if (!cacheData.isUseLocalConfigInfo() && cacheData.getFetchCount() == 0) {
String configInfo = getSnapshotConfiginfomation(cacheData.getDataId(), cacheData.getGroup());
if (configInfo != null) {
popConfigInfo(cacheData, configInfo);
}
}
}
}
}
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.");
}
}
/**
* Looks for a key with the same descriptor as the input key, which has a configuration that
* trimmed to a subset of the input key's.
*
* <p>Note that this is not referring to a <em>proper</em> subset; it's quite possible for a key
* to "trim" to a configuration equal to its configuration. That is, without anything being
* removed.
*
* <p>If such a key has been added to this cache, it is returned in a present {@link Optional}.
* Invoking this key will produce the same result as invoking the input key.
*
* <p>If no such key has been added to this cache, or if a key has been added to the cache and
* subsequently been the subject of an {@link #invalidate(KeyT)}, an absent Optional will be
* returned instead. No currently-valid key has trimmed to an equivalent configuration, and so the
* input key should be executed.
*/
public Optional<KeyT> get(KeyT input) {
DescriptorT descriptor = getDescriptorFor(input);
ConcurrentHashMap<ConfigurationT, KeyAndState<KeyT>> trimmingsOfDescriptor =
descriptors.get(descriptor);
if (trimmingsOfDescriptor == null) {
// There are no entries at all for this descriptor.
return Optional.empty();
}
ConfigurationT candidateConfiguration = getConfigurationFor(input);
for (Entry<ConfigurationT, KeyAndState<KeyT>> entry : trimmingsOfDescriptor.entrySet()) {
ConfigurationT trimmedConfig = entry.getKey();
KeyAndState<KeyT> canonicalKeyAndState = entry.getValue();
if (canSubstituteFor(candidateConfiguration, trimmedConfig, canonicalKeyAndState)) {
return Optional.of(canonicalKeyAndState.getKey());
}
}
return Optional.empty();
}
/**
* 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());
}
/**
* 获取探测更新的DataID的请求字符串
*
* @param localModifySet
* @return
*/
private String getProbeUpdateString() {
// 获取check的DataID:Group:MD5串
StringBuilder probeModifyBuilder = new StringBuilder();
for (Entry<String, ConcurrentHashMap<String, CacheData>> cacheDatasEntry : this.cache.entrySet()) {
String dataId = cacheDatasEntry.getKey();
ConcurrentHashMap<String, CacheData> cacheDatas = cacheDatasEntry.getValue();
if (null == cacheDatas) {
continue;
}
for (Entry<String, CacheData> cacheDataEntry : cacheDatas.entrySet()) {
final CacheData data = cacheDataEntry.getValue();
// 非使用本地配置,才去diamond server检查
if (!data.isUseLocalConfigInfo()) {
probeModifyBuilder.append(dataId).append(WORD_SEPARATOR);
if (null != cacheDataEntry.getValue().getGroup()
&& Constants.NULL != cacheDataEntry.getValue().getGroup()) {
probeModifyBuilder.append(cacheDataEntry.getValue().getGroup()).append(WORD_SEPARATOR);
}
else {
probeModifyBuilder.append(WORD_SEPARATOR);
}
if (null != cacheDataEntry.getValue().getMd5()
&& Constants.NULL != cacheDataEntry.getValue().getMd5()) {
probeModifyBuilder.append(cacheDataEntry.getValue().getMd5()).append(LINE_SEPARATOR);
}
else {
probeModifyBuilder.append(LINE_SEPARATOR);
}
}
}
}
String probeModifyString = probeModifyBuilder.toString();
return probeModifyString;
}
public void run() throws Exception {
TChannel tchannel = new TChannel.Builder("ping-client").build();
SubChannel subChannel = tchannel.makeSubChannel("ping-server");
final ConcurrentHashMap<String, AtomicInteger> msgs = new ConcurrentHashMap<>();
final CountDownLatch done = new CountDownLatch(requests);
for (int i = 0; i < requests; i++) {
JsonRequest<Ping> request = new JsonRequest.Builder<Ping>("ping-server", "ping")
.setBody(new Ping("{'key': 'ping?'}"))
.setHeader("some", "header")
.setTimeout(100 + i)
.build();
TFuture<JsonResponse<Pong>> f = subChannel.send(
request,
InetAddress.getByName(host),
port
);
f.addCallback(new TFutureCallback<JsonResponse<Pong>>() {
@Override
public void onResponse(JsonResponse<Pong> pongResponse) {
done.countDown();
String msg = pongResponse.toString();
AtomicInteger count = msgs.putIfAbsent(msg, new AtomicInteger(1));
if (count != null) {
count.incrementAndGet();
}
}
});
}
done.await();
for (Map.Entry<String, AtomicInteger> stringIntegerEntry : msgs.entrySet()) {
System.out.println(String.format("%s%n\tcount:%s",
stringIntegerEntry.getKey(), stringIntegerEntry.getValue()
));
}
tchannel.shutdown(false);
}
public static void writeServicesHtml(OutputStream outputStream,ConcurrentHashMap<String, ServiceHandler> serviceHandlerConcurrentHashMap) throws IOException {
writeHtmlStart(outputStream);
writeHeader(outputStream);
writeStyle(outputStream);
writeBodyStart(outputStream);
writeHead(outputStream);
writeTableStart(outputStream);
writeServiceHead(outputStream);
for(Map.Entry<String,ServiceHandler> entry:serviceHandlerConcurrentHashMap.entrySet()){
writeService(outputStream,entry.getKey(),entry.getValue());
}
writeTableEnd(outputStream);
writeBodyEnd(outputStream);
writeHtmlEnd(outputStream);
}
/**
* 获取缓存中,超时的key
* @param map
* @return
*/
public static List<String> getTimeoutCacheKeys(ConcurrentHashMap<String,String> map){
List<String> keys = new ArrayList<>();
long now = System.currentTimeMillis();
for (Map.Entry<String, String> entry : map.entrySet()) {
long cacheTime = getCacheTime(entry.getValue());
if(cacheTime == 0){
keys.add(entry.getKey());
}else if(now - cacheTime >= 2 * 24 * 60 * 60 * 1000){
//超时2天
keys.add(entry.getKey());
}
}
return keys;
}
/**
* 检查 关闭的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);
}
}
/**
* 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()));
}
}
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;
}