本文整理汇总了Java中java.util.concurrent.ConcurrentHashMap类的典型用法代码示例。如果您正苦于以下问题:Java ConcurrentHashMap类的具体用法?Java ConcurrentHashMap怎么用?Java ConcurrentHashMap使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ConcurrentHashMap类属于java.util.concurrent包,在下文中一共展示了ConcurrentHashMap类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: cacheStatement
import java.util.concurrent.ConcurrentHashMap; //导入依赖的package包/类
public boolean cacheStatement(CachedStatement proxy) {
@SuppressWarnings("unchecked")
ConcurrentHashMap<CacheKey,CachedStatement> cache =
(ConcurrentHashMap<CacheKey,CachedStatement>)pcon.getAttributes().get(STATEMENT_CACHE_ATTR);
if (proxy.getCacheKey()==null) {
return false;
} else if (cache.containsKey(proxy.getCacheKey())) {
return false;
} else if (cacheSize.get()>=maxCacheSize) {
return false;
} else if (cacheSize.incrementAndGet()>maxCacheSize) {
cacheSize.decrementAndGet();
return false;
} else {
//cache the statement
cache.put(proxy.getCacheKey(), proxy);
return true;
}
}
示例2: writeTransform
import java.util.concurrent.ConcurrentHashMap; //导入依赖的package包/类
@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);
}
}
示例3: clearExpired
import java.util.concurrent.ConcurrentHashMap; //导入依赖的package包/类
@Override
public boolean clearExpired(Date date) {
boolean clearedAny = false;
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) {
String name = entry.getKey();
Cookie cookie = entry.getValue();
if (cookie.isExpired(date)) {
// Clear cookies from local store
cookies.remove(name);
// Clear cookies from persistent store
prefsWriter.remove(COOKIE_NAME_PREFIX + name);
// We've cleared at least one
clearedAny = true;
}
}
// Update names in persistent store
if (clearedAny) {
prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
}
prefsWriter.apply();
return clearedAny;
}
示例4: OKEventBus
import java.util.concurrent.ConcurrentHashMap; //导入依赖的package包/类
OKEventBus(EventBusBuilder builder) {
logger = builder.getLogger();
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
mainThreadSupport = builder.getMainThreadSupport();
mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
backgroundPoster = new BackgroundPoster(this);
asyncPoster = new AsyncPoster(this);
indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
builder.strictMethodVerification, builder.ignoreGeneratedIndex);
logSubscriberExceptions = builder.logSubscriberExceptions;
logNoSubscriberMessages = builder.logNoSubscriberMessages;
sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
throwSubscriberException = builder.throwSubscriberException;
eventInheritance = builder.eventInheritance;
executorService = builder.executorService;
}
示例5: getPojoSetter
import java.util.concurrent.ConcurrentHashMap; //导入依赖的package包/类
public static final String getPojoSetter(ProtobufAttribute protobufAttribute, Field field) {
final String fieldName = field.getName();
final String upperClassName = field.getDeclaringClass().getCanonicalName();
// Look at the cache first
Map<String, String> map = CLASS_TO_FIELD_SETTERS_MAP_CACHE.get(upperClassName);
if (map != null) {
if (!map.isEmpty() && map.containsKey(fieldName)) {
return map.get(fieldName);
}
} else {
map = new ConcurrentHashMap<>();
}
final String upperCaseFirstFieldName = JStringUtils.upperCaseFirst(field.getName());
String setter = "set" + upperCaseFirstFieldName;
if (!protobufAttribute.pojoSetter().isEmpty()) {
return protobufAttribute.pojoSetter();
}
CLASS_TO_FIELD_SETTERS_MAP_CACHE.put(upperClassName, map);
return setter;
}
示例6: testMappedForEachEntrySequentially
import java.util.concurrent.ConcurrentHashMap; //导入依赖的package包/类
/**
* Mapped forEachEntrySequentially traverses the given
* transformations of all entries
*/
public void testMappedForEachEntrySequentially() {
LongAdder adder = new LongAdder();
ConcurrentHashMap<Long, Long> m = longMap();
m.forEachEntry(Long.MAX_VALUE, (Map.Entry<Long,Long> e) -> Long.valueOf(e.getKey().longValue() + e.getValue().longValue()),
(Long x) -> adder.add(x.longValue()));
assertEquals(adder.sum(), 3 * SIZE * (SIZE - 1) / 2);
}
示例7: initialize
import java.util.concurrent.ConcurrentHashMap; //导入依赖的package包/类
public void initialize() {
receivedAcks = new ConcurrentHashSet<>();
pingPonger = new GMSPingPonger();
// UUID logicalAddress = (UUID) channel.getAddress();
// IpAddress ipaddr = (IpAddress) channel.down(new Event(Event.GET_PHYSICAL_ADDRESS));
//
// myAddress = new JGAddress(logicalAddress, ipaddr);
myAddress = (JGAddress) channel.down(new Event(Event.GET_LOCAL_ADDRESS));
addressConversionMap = new ConcurrentHashMap<>(this.lastView.size());
List<InternalDistributedMember> members = this.lastView.getMembers();
for (InternalDistributedMember addr : members) {
SocketAddress sockaddr =
new InetSocketAddress(addr.getNetMember().getInetAddress(), addr.getPort());
addressConversionMap.put(sockaddr, addr);
}
isDebugEnabled = logger.isDebugEnabled();
resume();
}
示例8: removeTargetIfRequired
import java.util.concurrent.ConcurrentHashMap; //导入依赖的package包/类
/**
* Remove the target.
*
* @param subscribedMethods the subscribed methods.
* @param mTargetMap the target map.
* @param targetObject the target object.
*/
private void removeTargetIfRequired(ConcurrentHashMap<String, SubscriberHolder> subscribedMethods,
ConcurrentHashMap<Object,
ConcurrentHashMap<String, SubscriberHolder>> mTargetMap,
Object targetObject) {
if (subscribedMethods.size() == 0) {
mTargetMap.remove(targetObject);
}
}
示例9: notify
import java.util.concurrent.ConcurrentHashMap; //导入依赖的package包/类
@Override
protected void notify(URL url, NotifyListener listener, List<URL> urls) {
if (url == null) {
throw new IllegalArgumentException("notify url == null");
}
if (listener == null) {
throw new IllegalArgumentException("notify listener == null");
}
try {
doNotify(url, listener, urls);
} catch (Exception t) {
// 将失败的通知请求记录到失败列表,定时重试
Map<NotifyListener, List<URL>> listeners = failedNotified.get(url);
if (listeners == null) {
failedNotified.putIfAbsent(url, new ConcurrentHashMap<NotifyListener, List<URL>>());
listeners = failedNotified.get(url);
}
listeners.put(listener, urls);
logger.error("Failed to notify for subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t);
}
}
示例10: buildVocabulary
import java.util.concurrent.ConcurrentHashMap; //导入依赖的package包/类
private ConcurrentHashMap<String, Integer> buildVocabulary(InputStream input) throws IOException {
ConcurrentHashMap<String, Integer> vocabulary = new ConcurrentHashMap<>();
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
String l = buffer.readLine();
while (l != null ) {
String p[] = l.split(",");
if (p[1].length() > 1) {
vocabulary.put(p[0], Integer.valueOf(p[1]));
}
l = buffer.readLine();
}
}
return vocabulary;
}
示例11: preferProportionalFonts
import java.util.concurrent.ConcurrentHashMap; //导入依赖的package包/类
public synchronized void preferProportionalFonts() {
if (FontUtilities.isLogging()) {
FontUtilities.getLogger()
.info("Entered preferProportionalFonts().");
}
/* If no proportional fonts are configured, there's no need
* to take any action.
*/
if (!FontConfiguration.hasMonoToPropMap()) {
return;
}
if (!maybeMultiAppContext()) {
if (gPropPref == true) {
return;
}
gPropPref = true;
createCompositeFonts(fontNameCache, gLocalePref, gPropPref);
_usingAlternateComposites = true;
} else {
AppContext appContext = AppContext.getAppContext();
if (appContext.get(proportionalFontKey) == proportionalFontKey) {
return;
}
appContext.put(proportionalFontKey, proportionalFontKey);
boolean acLocalePref =
appContext.get(localeFontKey) == localeFontKey;
ConcurrentHashMap<String, Font2D>
altNameCache = new ConcurrentHashMap<String, Font2D> ();
/* If there is an existing hashtable, we can drop it. */
appContext.put(CompositeFont.class, altNameCache);
_usingPerAppContextComposites = true;
createCompositeFonts(altNameCache, acLocalePref, true);
}
}
示例12: whichTopicByConsumer
import java.util.concurrent.ConcurrentHashMap; //导入依赖的package包/类
/**
* 获取消费者分组消费的topic;
* @param group
* @return
*/
public Set<String> whichTopicByConsumer(final String group) {
Set<String> topics = new HashSet<String>();
Iterator<Entry<String, ConcurrentHashMap<Integer, Long>>> it = this.offsetTable.entrySet().iterator();
while (it.hasNext()) {
Entry<String, ConcurrentHashMap<Integer, Long>> next = it.next();
String topicAtGroup = next.getKey();
String[] arrays = topicAtGroup.split(TOPIC_GROUP_SEPARATOR);
if (arrays != null && arrays.length == 2) {
if (group.equals(arrays[1])) {
topics.add(arrays[0]);
}
}
}
return topics;
}
示例13: addCnxn
import java.util.concurrent.ConcurrentHashMap; //导入依赖的package包/类
private void addCnxn(NIOServerCnxn cnxn) {
InetAddress addr = cnxn.getSocketAddress();
Set<NIOServerCnxn> set = ipMap.get(addr);
if (set == null) {
// in general we will see 1 connection from each
// host, setting the initial cap to 2 allows us
// to minimize mem usage in the common case
// of 1 entry -- we need to set the initial cap
// to 2 to avoid rehash when the first entry is added
// Construct a ConcurrentHashSet using a ConcurrentHashMap
set = Collections.newSetFromMap(
new ConcurrentHashMap<NIOServerCnxn, Boolean>(2));
// Put the new set in the map, but only if another thread
// hasn't beaten us to it
Set<NIOServerCnxn> existingSet = ipMap.putIfAbsent(addr, set);
if (existingSet != null) {
set = existingSet;
}
}
set.add(cnxn);
cnxns.add(cnxn);
touchCnxn(cnxn);
}
示例14: clearExpired
import java.util.concurrent.ConcurrentHashMap; //导入依赖的package包/类
@Override
public boolean clearExpired(Date date) {
boolean clearedAny = false;
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) {
String name = entry.getKey();
Cookie cookie = entry.getValue();
if (cookie.isExpired(date)) {
// Clear cookies from local store
cookies.remove(name);
// Clear cookies from persistent store
prefsWriter.remove(COOKIE_NAME_PREFIX + name);
// We've cleared at least one
clearedAny = true;
}
}
// Update names in persistent store
if (clearedAny) {
// This prevents map.keySet to compile to a Java 8+ KeySetView return type
Map<String, Cookie> map = cookies;
prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", map.keySet()));
}
prefsWriter.apply();
return clearedAny;
}
示例15: init
import java.util.concurrent.ConcurrentHashMap; //导入依赖的package包/类
@SuppressWarnings("unchecked")
public static void init(String esInfo, String context) {
if (null == info) {
info = JSONHelper.toObject(esInfo, Map.class);
}
if (null == httpAsyncClient) {
Map<String, Integer> httpParamsMap = JSONHelper.toObject(context, Map.class);
httpAsyncClient = HttpAsyncClientFactory.build(httpParamsMap.get("max.con"),
httpParamsMap.get("max.tot.con"), httpParamsMap.get("sock.time.out"),
httpParamsMap.get("con.time.out"), httpParamsMap.get("req.time.out"));
}
if (null == connectionMgrPool) {
connectionMgrPool = new ConcurrentHashMap<String, ConnectionFailoverMgr>();
String forwarUrl = getInfoValue("forwar.url");
forwarUrl = forwarUrl.trim().replace("\n", "").replace("\r", "");
ConnectionFailoverMgr cfm = ConnectionFailoverMgrHelper.getConnectionFailoverMgr(forwarUrl, 60000);
connectionMgrPool.put("es.info.forwar.url", cfm);
}
}