Java 类java.util.concurrent.ConcurrentHashMap 实例源码

项目:apache-tomcat-7.0.73-with-comment    文件:StatementCache.java   
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;
    }
}
项目:monarch    文件:AutoSerializableJUnitTest.java   
@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);
  }
}
项目:OKEventBus    文件:OKEventBus.java   
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;
}
项目:rongyunDemo    文件:PersistentCookieStore.java   
@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;
}
项目:saluki    文件:ProtobufSerializerUtils.java   
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;
}
项目:openjdk-jdk10    文件:ConcurrentHashMap8Test.java   
/**
 * 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);
}
项目:monarch    文件:GMSQuorumChecker.java   
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();
}
项目:NYBus    文件:NYBusDriver.java   
/**
 * 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);
    }
}
项目:dubbox-hystrix    文件:FailbackRegistry.java   
@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);
    }
}
项目:tensorflow-spring-cloud-stream-app-starters    文件:WordVocabulary.java   
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;
    }
项目:jdk8u-jdk    文件:SunFontManager.java   
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);
    }
}
项目:reading-and-annotate-rocketmq-3.4.6    文件:ConsumerOffsetManager.java   
/**
 * 获取消费者分组消费的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;
}
项目:https-github.com-apache-zookeeper    文件:NIOServerCnxnFactory.java   
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);
}
项目:AndroidAsyncHTTP    文件:PersistentCookieStore.java   
@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;
}
项目:uavstack    文件:EsRestServlet.java   
@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);
    }

}
项目:ForeverLibrary    文件:MyCookieStore.java   
public MyCookieStore() {
    cookiePrefs = ToolCache.getContext().getSharedPreferences(COOKIE_PREFS, Context.MODE_PRIVATE);
    cookies = new HashMap<>();

    //将持久化的cookies缓存到内存中,数据结构为 Map<Url.host, Map<Cookie.name, Cookie>>
    Map<String, ?> prefsMap = cookiePrefs.getAll();
    for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
        if ((entry.getValue()) != null && !entry.getKey().startsWith(COOKIE_NAME_PREFIX)) {
            //获取url对应的所有cookie的key,用","分割
            String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
            for (String name : cookieNames) {
                //根据对应cookie的Key,从xml中获取cookie的真实值
                String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
                if (encodedCookie != null) {
                    Cookie decodedCookie = decodeCookie(encodedCookie);
                    if (decodedCookie != null) {
                        if (!cookies.containsKey(entry.getKey()))
                            cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());
                        cookies.get(entry.getKey()).put(name, decodedCookie);
                    }
                }
            }
        }
    }
}
项目:GitHub    文件:PersistentCookieStore.java   
/**
 * Construct a persistent cookie store.
 *
 * @param context Context to attach cookie store to
 */
public PersistentCookieStore(Context context) {
    cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
    cookies = new ConcurrentHashMap<String, Cookie>();

    // Load any previously stored cookies into the store
    String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE, null);
    if (storedCookieNames != null) {
        String[] cookieNames = TextUtils.split(storedCookieNames, ",");
        for (String name : cookieNames) {
            String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
            if (encodedCookie != null) {
                Cookie decodedCookie = decodeCookie(encodedCookie);
                if (decodedCookie != null) {
                    cookies.put(name, decodedCookie);
                }
            }
        }

        // Clear out expired cookies
        clearExpired(new Date());
    }
}
项目:reading-and-annotate-rocketmq-3.4.6    文件:DefaultMessageStore.java   
@Override
public int cleanUnusedTopic(Set<String> topics) {
    Iterator<Entry<String, ConcurrentHashMap<Integer, ConsumeQueue>>> it = this.consumeQueueTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, ConcurrentHashMap<Integer, ConsumeQueue>> next = it.next();
        String topic = next.getKey();
        if (!topics.contains(topic) && !topic.equals(ScheduleMessageService.SCHEDULE_TOPIC)) {
            ConcurrentHashMap<Integer, ConsumeQueue> queueTable = next.getValue();
            for (ConsumeQueue cq : queueTable.values()) {
                cq.destroy();
                log.info("cleanUnusedTopic: {} {} ConsumeQueue cleaned",//
                    cq.getTopic(), //
                    cq.getQueueId() //
                );

                this.commitLog.removeQueurFromTopicQueueTable(cq.getTopic(), cq.getQueueId());
            }
            it.remove();

            log.info("cleanUnusedTopic: {},topic destroyed", topic);
        }
    }

    return 0;
}
项目:OpenJSharp    文件:ClassLoader.java   
private void checkCerts(String name, CodeSource cs) {
    int i = name.lastIndexOf('.');
    String pname = (i == -1) ? "" : name.substring(0, i);

    Certificate[] certs = null;
    if (cs != null) {
        certs = cs.getCertificates();
    }
    Certificate[] pcerts = null;
    if (parallelLockMap == null) {
        synchronized (this) {
            pcerts = package2certs.get(pname);
            if (pcerts == null) {
                package2certs.put(pname, (certs == null? nocerts:certs));
            }
        }
    } else {
        pcerts = ((ConcurrentHashMap<String, Certificate[]>)package2certs).
            putIfAbsent(pname, (certs == null? nocerts:certs));
    }
    if (pcerts != null && !compareCerts(pcerts, certs)) {
        throw new SecurityException("class \""+ name +
             "\"'s signer information does not match signer information of other classes in the same package");
    }
}
项目:hadoop    文件:TestClientRMService.java   
public ClientRMService createRMService() throws IOException {
  YarnScheduler yarnScheduler = mockYarnScheduler();
  RMContext rmContext = mock(RMContext.class);
  mockRMContext(yarnScheduler, rmContext);
  ConcurrentHashMap<ApplicationId, RMApp> apps = getRMApps(rmContext,
      yarnScheduler);
  when(rmContext.getRMApps()).thenReturn(apps);
  when(rmContext.getYarnConfiguration()).thenReturn(new Configuration());
  RMAppManager appManager = new RMAppManager(rmContext, yarnScheduler, null,
      mock(ApplicationACLsManager.class), new Configuration());
  when(rmContext.getDispatcher().getEventHandler()).thenReturn(
      new EventHandler<Event>() {
        public void handle(Event event) {
        }
      });

  ApplicationACLsManager mockAclsManager = mock(ApplicationACLsManager.class);
  QueueACLsManager mockQueueACLsManager = mock(QueueACLsManager.class);
  when(
      mockQueueACLsManager.checkAccess(any(UserGroupInformation.class),
          any(QueueACL.class), anyString())).thenReturn(true);
  return new ClientRMService(rmContext, yarnScheduler, appManager,
      mockAclsManager, mockQueueACLsManager, null);
}
项目:jdk8u-jdk    文件:CalendarSystem.java   
private static void initNames() {
    ConcurrentMap<String,String> nameMap = new ConcurrentHashMap<>();

    // Associate a calendar name with its class name and the
    // calendar class name with its date class name.
    StringBuilder clName = new StringBuilder();
    for (int i = 0; i < namePairs.length; i += 2) {
        clName.setLength(0);
        String cl = clName.append(PACKAGE_NAME).append(namePairs[i+1]).toString();
        nameMap.put(namePairs[i], cl);
    }
    synchronized (CalendarSystem.class) {
        if (!initialized) {
            names = nameMap;
            calendars = new ConcurrentHashMap<>();
            initialized = true;
        }
    }
}
项目:github-test    文件:FailbackRegistry.java   
@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);
    }
}
项目:x7    文件:AsyncRepository.java   
protected static void put(Class clz, List list) {
    Parsed parsed = Parser.get(clz);
    Map<String, Object> map1 = new ConcurrentHashMap<String, Object>();
    map.put(clz, map1);

    try {
        for (Object obj : list) {
            long idOne = parsed.getKeyField(X.KEY_ONE).getLong(obj);
            String key = getKey(clz, idOne);
            map1.put(key, obj);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
项目:hadoop-oss    文件:NetgroupCache.java   
/**
 * Add group to cache
 *
 * @param group name of the group to add to cache
 * @param users list of users for a given group
 */
public static void add(String group, List<String> users) {
  for (String user : users) {
    Set<String> userGroups = userToNetgroupsMap.get(user);
    // ConcurrentHashMap does not allow null values; 
    // So null value check can be used to check if the key exists
    if (userGroups == null) {
      //Generate a ConcurrentHashSet (backed by the keyset of the ConcurrentHashMap)
      userGroups =
          Collections.newSetFromMap(new ConcurrentHashMap<String,Boolean>());
      Set<String> currentSet = userToNetgroupsMap.putIfAbsent(user, userGroups);
      if (currentSet != null) {
        userGroups = currentSet;
      }
    }
    userGroups.add(group);
  }
}
项目:datarouter    文件:AtomicCounter.java   
public AtomicCounter(long startTimeMs, long lengthMs){
    this.startTimeMs = startTimeMs;
    this.lengthMs = lengthMs;
    this.countByKey = new ConcurrentHashMap<>(INITIAL_CAPACITY);
    Thread createdByThread = Thread.currentThread();
    this.createdByThreadId = createdByThread.getId() + "-" + createdByThread.getName();
}
项目:java-velocypack    文件:VPackCache.java   
public VPackCache(final VPackFieldNamingStrategy fieldNamingStrategy,
    final Map<Class<? extends Annotation>, VPackAnnotationFieldFilter<? extends Annotation>> annotationFieldFilter,
    final Map<Class<? extends Annotation>, VPackAnnotationFieldNaming<? extends Annotation>> annotationFieldNaming) {
    super();
    cache = new ConcurrentHashMap<Type, Map<String, FieldInfo>>();
    fieldComparator = new Comparator<Map.Entry<String, FieldInfo>>() {
        @Override
        public int compare(final Entry<String, FieldInfo> o1, final Entry<String, FieldInfo> o2) {
            return o1.getKey().compareTo(o2.getKey());
        }
    };
    this.fieldNamingStrategy = fieldNamingStrategy;
    this.annotationFilter = annotationFieldFilter;
    this.annotationFieldNaming = annotationFieldNaming;
}
项目:monarch    文件:PartitionedRegionSingleHopDUnitTest.java   
public static void verifyMetadata(Map<Integer, List<BucketServerLocation66>> clientMap) {
  final PartitionedRegion pr = (PartitionedRegion) region;
  ConcurrentHashMap<Integer, Set<ServerBucketProfile>> serverMap =
      pr.getRegionAdvisor().getAllClientBucketProfilesTest();
  assertEquals(clientMap.size(), serverMap.size());
  assertTrue(clientMap.keySet().containsAll(serverMap.keySet()));
  for (Map.Entry<Integer, List<BucketServerLocation66>> entry : clientMap.entrySet()) {
    int bucketId = entry.getKey();
    List<BucketServerLocation66> list = entry.getValue();
    BucketServerLocation66 primaryBSL = null;
    int primaryCnt = 0;
    for (BucketServerLocation66 bsl : list) {
      if (bsl.isPrimary()) {
        primaryBSL = bsl;
        primaryCnt++;
      }
    }
    assertTrue(primaryCnt == 1);
    Set<ServerBucketProfile> set = serverMap.get(bucketId);
    assertEquals(list.size(), set.size());
    primaryCnt = 0;
    for (ServerBucketProfile bp : set) {
      ServerLocation sl = (ServerLocation) bp.bucketServerLocations.toArray()[0];
      assertTrue(list.contains(sl));
      // should be only one primary
      if (bp.isPrimary) {
        primaryCnt++;
        assertTrue(primaryBSL.equals(sl));
      }
    }
    assertTrue(primaryCnt == 1);
  }
}
项目:dubbocloud    文件:LogFilter.java   
private void archieveId(ServletRequest request) throws Throwable {
    @SuppressWarnings("unchecked")
    Map<String, String> globalMap = CallChainContext.getContext().get();
    String currentIdValue = "";
    String traceIdValue = "";
    String spanIdValue = "";

    if (null == globalMap) {
        globalMap = new ConcurrentHashMap<String, String>();
        CallChainContext.getContext().add(globalMap);
    }

    traceIdValue = globalMap.get(CallChainContext.TRACEID);
    if (StringUtils.isEmpty(traceIdValue)) {
        traceIdValue = Long.toHexString(System.currentTimeMillis());
    }

    spanIdValue = globalMap.get(CallChainContext.SPANID);
    if (StringUtils.isEmpty(spanIdValue)) {
        spanIdValue = CallChainContext.DEFAULT_ID;
    }


    globalMap.put(CallChainContext.TRACEID, traceIdValue);
    globalMap.put(CallChainContext.SPANID, spanIdValue);
    currentIdValue = globalMap.get(CallChainContext.CURRENTID);
    if (StringUtils.isEmpty(currentIdValue)) {
        //currentIdValue = CallChainContext.DEFAULT_ID;
        globalMap.put(CallChainContext.CURRENTID, spanIdValue);

    }

    RpcContext.getContext().setAttachment(CallChainContext.TRACEID, traceIdValue);
    RpcContext.getContext().setAttachment(CallChainContext.SPANID, spanIdValue);

}
项目:angel    文件:ServerPartition.java   
/**
 * Create a new Server partition,include load rows.
 *
 * @param partitionKey the partition meta
 * @param rowType      the row type
 */
public ServerPartition(PartitionKey partitionKey, RowType rowType) {
  this.state = PartitionState.INITIALIZING;
  this.partitionKey = partitionKey;
  this.rowType = rowType;
  this.rows = new ConcurrentHashMap<Integer, ServerRow>();
  this.clock = 0;
}
项目:L2J-Global    文件:Duel.java   
public void registerDebuff(Skill debuff)
{
    if (_debuffs == null)
    {
        _debuffs = ConcurrentHashMap.newKeySet();
    }

    _debuffs.add(debuff);
}
项目:jsf-core    文件:InterfaceVo.java   
/**
 * 赋值
 * @param map
 */
public void putAllParamRouterMap(Map<String, List<String>> map) {
    if (map != null && !map.isEmpty()) {
        if (paramRouterMap == null) {
            paramRouterMap = new ConcurrentHashMap<String, List<String>>(1, loadFactor, 1);
        }
        paramRouterMap.putAll(map);
    }
}
项目:reading-and-annotate-rocketmq-3.4.6    文件:DefaultMessageStore.java   
public void truncateDirtyLogicFiles(long phyOffset) {
    ConcurrentHashMap<String, ConcurrentHashMap<Integer, ConsumeQueue>> tables = DefaultMessageStore.this.consumeQueueTable;

    for (ConcurrentHashMap<Integer, ConsumeQueue> maps : tables.values()) {
        for (ConsumeQueue logic : maps.values()) {
            logic.truncateDirtyLogicFiles(phyOffset);
        }
    }
}
项目:hadoop    文件:Configuration.java   
/** 
 * A new configuration with the same settings cloned from another.
 * 
 * @param other the configuration from which to clone settings.
 */
@SuppressWarnings("unchecked")
public Configuration(Configuration other) {
 this.resources = (ArrayList<Resource>) other.resources.clone();
 synchronized(other) {
   if (other.properties != null) {
     this.properties = (Properties)other.properties.clone();
   }

   if (other.overlay!=null) {
     this.overlay = (Properties)other.overlay.clone();
   }

   this.updatingResource = new ConcurrentHashMap<String, String[]>(
       other.updatingResource);
   this.finalParameters = Collections.newSetFromMap(
       new ConcurrentHashMap<String, Boolean>());
   this.finalParameters.addAll(other.finalParameters);
 }

  synchronized(Configuration.class) {
    REGISTRY.put(this, null);
  }
  this.classLoader = other.classLoader;
  this.loadDefaults = other.loadDefaults;
  setQuietMode(other.getQuietMode());
}
项目:OpenJSharp    文件:Activation.java   
/**
 * Previous versions used HashMap instead of ConcurrentHashMap.
 * Replace any HashMaps found during deserialization with
 * ConcurrentHashMaps.
 */
private void readObject(ObjectInputStream ois)
    throws IOException, ClassNotFoundException
{
    ois.defaultReadObject();
    if (! (groupTable instanceof ConcurrentHashMap)) {
        groupTable = new ConcurrentHashMap<>(groupTable);
    }
    if (! (idTable instanceof ConcurrentHashMap)) {
        idTable = new ConcurrentHashMap<>(idTable);
    }
}
项目:koryphe    文件:SimpleClassNameCache.java   
private static Map<String, Set<Class>> createIdToClasses() {
    final Map<String, Set<Class>> map = new ConcurrentHashMap<>();
    for (final Class baseClass : baseClasses) {
        addSimpleClassNames(map, baseClass);
    }
    for (final Class clazz : ReflectionUtil.getAnnotatedTypes(JsonSimpleClassName.class)) {
        addSimpleClassName(map, clazz);
    }

    return map;
}
项目:boohee_v5.6    文件:h.java   
private static Map<Object, Object> a(Type type) {
    Class cls = type;
    while (cls != Properties.class) {
        if (cls == Hashtable.class) {
            return new Hashtable();
        }
        if (cls == IdentityHashMap.class) {
            return new IdentityHashMap();
        }
        if (cls == SortedMap.class || cls == TreeMap.class) {
            return new TreeMap();
        }
        if (cls == ConcurrentMap.class || cls == ConcurrentHashMap.class) {
            return new ConcurrentHashMap();
        }
        if (cls == Map.class || cls == HashMap.class) {
            return new HashMap();
        }
        if (cls == LinkedHashMap.class) {
            return new LinkedHashMap();
        }
        if (cls instanceof ParameterizedType) {
            cls = ((ParameterizedType) cls).getRawType();
        } else {
            Class cls2 = cls;
            if (cls2.isInterface()) {
                throw new IllegalArgumentException("unsupport type " + cls);
            }
            try {
                return (Map) cls2.newInstance();
            } catch (Throwable e) {
                throw new IllegalArgumentException("unsupport type " + cls, e);
            }
        }
    }
    return new Properties();
}
项目:openjdk-jdk10    文件:ClassLoader.java   
/**
 * Returns the ConcurrentHashMap used as a storage for ClassLoaderValue(s)
 * associated with this ClassLoader, creating it if it doesn't already exist.
 */
ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap() {
    ConcurrentHashMap<?, ?> map = classLoaderValueMap;
    if (map == null) {
        map = new ConcurrentHashMap<>();
        boolean set = trySetObjectField("classLoaderValueMap", map);
        if (!set) {
            // beaten by someone else
            map = classLoaderValueMap;
        }
    }
    return map;
}
项目:lams    文件:JdbcTypeJavaClassMappings.java   
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;
}
项目:L2J-Global    文件:WarpedSpaceManager.java   
public void addWarpedSpace(L2Character creature, int radius)
{
    if (_warpedSpace == null)
    {
        synchronized (this)
        {
            if (_warpedSpace == null)
            {
                _warpedSpace = new ConcurrentHashMap<>();
            }
        }
    }
    _warpedSpace.put(creature, new WarpedSpaceHolder(creature, radius));
}
项目:openjdk-jdk10    文件:CryptoPermissions.java   
private void readObject(ObjectInputStream s)
    throws IOException, ClassNotFoundException {
    ObjectInputStream.GetField fields = s.readFields();
    @SuppressWarnings("unchecked")
    Hashtable<String,PermissionCollection> permTable =
            (Hashtable<String,PermissionCollection>)
            (fields.get("perms", null));
    if (permTable != null) {
        perms = new ConcurrentHashMap<>(permTable);
    } else {
        perms = new ConcurrentHashMap<>();
    }
}