当前位置: 首页>>代码示例>>Java>>正文


Java ConcurrentHashMap类代码示例

本文整理汇总了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;
    }
}
 
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:20,代码来源:StatementCache.java

示例2: 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;
}
 
开发者ID:zqHero,项目名称:rongyunDemo,代码行数:29,代码来源:PersistentCookieStore.java

示例3: 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);
  }
}
 
开发者ID:ampool,项目名称:monarch,代码行数:19,代码来源:AutoSerializableJUnitTest.java

示例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;
}
 
开发者ID:AweiLoveAndroid,项目名称:OKEventBus,代码行数:21,代码来源:OKEventBus.java

示例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;
}
 
开发者ID:venus-boot,项目名称:saluki,代码行数:21,代码来源:ProtobufSerializerUtils.java

示例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);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:12,代码来源:ConcurrentHashMap8Test.java

示例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();
}
 
开发者ID:ampool,项目名称:monarch,代码行数:22,代码来源:GMSQuorumChecker.java

示例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);
    }
}
 
开发者ID:MindorksOpenSource,项目名称:NYBus,代码行数:16,代码来源:NYBusDriver.java

示例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);
    }
}
 
开发者ID:yunhaibin,项目名称:dubbox-hystrix,代码行数:22,代码来源:FailbackRegistry.java

示例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;
	}
 
开发者ID:tzolov,项目名称:tensorflow-spring-cloud-stream-app-starters,代码行数:17,代码来源:WordVocabulary.java

示例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);
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:36,代码来源:SunFontManager.java

示例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;
}
 
开发者ID:y123456yz,项目名称:reading-and-annotate-rocketmq-3.4.6,代码行数:23,代码来源:ConsumerOffsetManager.java

示例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);
}
 
开发者ID:didichuxing2,项目名称:https-github.com-apache-zookeeper,代码行数:25,代码来源:NIOServerCnxnFactory.java

示例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;
}
 
开发者ID:Vorlonsoft,项目名称:AndroidAsyncHTTP,代码行数:31,代码来源:PersistentCookieStore.java

示例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);
    }

}
 
开发者ID:uavorg,项目名称:uavstack,代码行数:24,代码来源:EsRestServlet.java


注:本文中的java.util.concurrent.ConcurrentHashMap类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。