Java Code Examples for java.util.concurrent.ConcurrentHashMap

The following are top voted examples for showing how to use java.util.concurrent.ConcurrentHashMap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: apache-tomcat-7.0.73-with-comment   File: StatementCache.java   View source code 7 votes vote down vote up
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;
    }
}
 
Example 2
Project: monarch   File: AutoSerializableJUnitTest.java   View source code 7 votes vote down vote up
@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 3
Project: OKEventBus   File: OKEventBus.java   View source code 6 votes vote down vote up
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;
}
 
Example 4
Project: rongyunDemo   File: PersistentCookieStore.java   View source code 6 votes vote down vote up
@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;
}
 
Example 5
Project: saluki   File: ProtobufSerializerUtils.java   View source code 6 votes vote down vote up
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;
}
 
Example 6
Project: openjdk-jdk10   File: ConcurrentHashMap8Test.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 7
Project: monarch   File: GMSQuorumChecker.java   View source code 6 votes vote down vote up
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();
}
 
Example 8
Project: NYBus   File: NYBusDriver.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 9
Project: dubbox-hystrix   File: FailbackRegistry.java   View source code 6 votes vote down vote up
@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);
    }
}
 
Example 10
Project: tensorflow-spring-cloud-stream-app-starters   File: WordVocabulary.java   View source code 6 votes vote down vote up
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;
	}
 
Example 11
Project: jdk8u-jdk   File: SunFontManager.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 12
Project: reading-and-annotate-rocketmq-3.4.6   File: ConsumerOffsetManager.java   View source code 6 votes vote down vote up
/**
 * 获取消费者分组消费的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;
}
 
Example 13
Project: https-github.com-apache-zookeeper   File: NIOServerCnxnFactory.java   View source code 6 votes vote down vote up
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);
}
 
Example 14
Project: AndroidAsyncHTTP   File: PersistentCookieStore.java   View source code 6 votes vote down vote up
@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;
}
 
Example 15
Project: uavstack   File: EsRestServlet.java   View source code 6 votes vote down vote up
@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);
    }

}
 
Example 16
Project: ForeverLibrary   File: MyCookieStore.java   View source code 6 votes vote down vote up
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);
                    }
                }
            }
        }
    }
}
 
Example 17
Project: GitHub   File: PersistentCookieStore.java   View source code 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example 18
Project: reading-and-annotate-rocketmq-3.4.6   File: DefaultMessageStore.java   View source code 6 votes vote down vote up
@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;
}
 
Example 19
Project: OpenJSharp   File: ClassLoader.java   View source code 6 votes vote down vote up
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");
    }
}
 
Example 20
Project: hadoop   File: TestClientRMService.java   View source code 6 votes vote down vote up
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);
}
 
Example 21
Project: jdk8u-jdk   File: CalendarSystem.java   View source code 6 votes vote down vote up
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;
        }
    }
}
 
Example 22
Project: github-test   File: FailbackRegistry.java   View source code 6 votes vote down vote up
@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);
    }
}
 
Example 23
Project: x7   File: AsyncRepository.java   View source code 6 votes vote down vote up
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();
	}

}
 
Example 24
Project: hadoop-oss   File: NetgroupCache.java   View source code 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example 25
Project: datarouter   File: AtomicCounter.java   View source code 5 votes vote down vote up
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();
}
 
Example 26
Project: java-velocypack   File: VPackCache.java   View source code 5 votes vote down vote up
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;
}
 
Example 27
Project: monarch   File: PartitionedRegionSingleHopDUnitTest.java   View source code 5 votes vote down vote up
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);
  }
}
 
Example 28
Project: dubbocloud   File: LogFilter.java   View source code 5 votes vote down vote up
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);

}
 
Example 29
Project: angel   File: ServerPartition.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 30
Project: L2J-Global   File: Duel.java   View source code 5 votes vote down vote up
public void registerDebuff(Skill debuff)
{
	if (_debuffs == null)
	{
		_debuffs = ConcurrentHashMap.newKeySet();
	}
	
	_debuffs.add(debuff);
}
 
Example 31
Project: jsf-core   File: InterfaceVo.java   View source code 5 votes vote down vote up
/**
 * 赋值
 * @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);
    }
}
 
Example 32
Project: reading-and-annotate-rocketmq-3.4.6   File: DefaultMessageStore.java   View source code 5 votes vote down vote up
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);
        }
    }
}
 
Example 33
Project: hadoop   File: Configuration.java   View source code 5 votes vote down vote up
/** 
 * 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());
}
 
Example 34
Project: OpenJSharp   File: Activation.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 35
Project: koryphe   File: SimpleClassNameCache.java   View source code 5 votes vote down vote up
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;
}
 
Example 36
Project: boohee_v5.6   File: h.java   View source code 5 votes vote down vote up
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();
}
 
Example 37
Project: openjdk-jdk10   File: ClassLoader.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 38
Project: lams   File: JdbcTypeJavaClassMappings.java   View source code 5 votes vote down vote up
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;
}
 
Example 39
Project: L2J-Global   File: WarpedSpaceManager.java   View source code 5 votes vote down vote up
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));
}
 
Example 40
Project: openjdk-jdk10   File: CryptoPermissions.java   View source code 5 votes vote down vote up
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<>();
    }
}