Java Code Examples for java.util.concurrent.ConcurrentMap#get()

The following examples show how to use java.util.concurrent.ConcurrentMap#get() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: actframework   File: EventBus.java    License: Apache License 2.0 6 votes vote down vote up
private synchronized EventBus _bind(final ConcurrentMap<Class<? extends EventObject>, List<ActEventListener>> listeners, final Class<? extends EventObject> eventType, final ActEventListener listener, int ttl) {
    eventsWithActListeners.add(eventType);
    List<ActEventListener> list = listeners.get(eventType);
    if (null == list) {
        List<ActEventListener> newList = new ArrayList<>();
        list = listeners.putIfAbsent(eventType, newList);
        if (null == list) {
            list = newList;
        }
    }
    if (addIntoListWithOrder(list, listener)) {
        if (ttl > 0) {
            app().jobManager().delay(new Runnable() {
                @Override
                public void run() {
                    synchronized (EventBus.this) {
                        _unbind(listeners, eventType, listener);
                    }
                }
            }, ttl, TimeUnit.SECONDS);
        }
    }
    return this;
}
 
Example 2
Source Project: rocketmq-4.3.0   File: PullAPIWrapper.java    License: Apache License 2.0 6 votes vote down vote up
private String computPullFromWhichFilterServer(final String topic, final String brokerAddr)
        throws MQClientException {
//        获取topic路由=》
        ConcurrentMap<String, TopicRouteData> topicRouteTable = this.mQClientFactory.getTopicRouteTable();
        if (topicRouteTable != null) {
            TopicRouteData topicRouteData = topicRouteTable.get(topic);
            List<String> list = topicRouteData.getFilterServerTable().get(brokerAddr);

//            随机策略
            if (list != null && !list.isEmpty()) {
                return list.get(randomNum() % list.size());
            }
        }

        throw new MQClientException("Find Filter Server Failed, Broker Addr: " + brokerAddr + " topic: "
            + topic, null);
    }
 
Example 3
Source Project: dubbox   File: SimpleRegistryService.java    License: Apache License 2.0 6 votes vote down vote up
public void subscribe(URL url, NotifyListener listener) {
    if (getUrl().getPort() == 0) {
        URL registryUrl = RpcContext.getContext().getUrl();
        if (registryUrl != null && registryUrl.getPort() > 0
        		&& RegistryService.class.getName().equals(registryUrl.getPath())) {
            super.setUrl(registryUrl);
            super.register(registryUrl);
        }
    }
    String client = RpcContext.getContext().getRemoteAddressString();
    ConcurrentMap<URL, Set<NotifyListener>> clientListeners = remoteSubscribed.get(client);
    if (clientListeners == null) {
        remoteSubscribed.putIfAbsent(client, new ConcurrentHashMap<URL, Set<NotifyListener>>());
        clientListeners = remoteSubscribed.get(client);
    }
    Set<NotifyListener> listeners = clientListeners.get(url);
    if (listeners == null) {
        clientListeners.putIfAbsent(url, new ConcurrentHashSet<NotifyListener>());
        listeners = clientListeners.get(url);
    }
    listeners.add(listener);
    super.subscribe(url, listener);
    subscribed(url, listener);
}
 
Example 4
Source Project: light   File: AbstractTagRule.java    License: Apache License 2.0 6 votes vote down vote up
protected List<String> getTagEntityList(String host, String tagId) {
    List<String> list = null;
    Map<String, Object> categoryMap = ServiceLocator.getInstance().getMemoryImage("categoryMap");
    ConcurrentMap<Object, Object> listCache = (ConcurrentMap<Object, Object>)categoryMap.get("listCache");
    if(listCache == null) {
        listCache = new ConcurrentLinkedHashMap.Builder<Object, Object>()
                .maximumWeightedCapacity(200)
                .build();
        categoryMap.put("listCache", listCache);
    } else {
        list = (List<String>)listCache.get(host + tagId);
    }
    if(list == null) {
        list = getTagEntityListDb(host, tagId);
        if(list != null) {
            listCache.put(host + tagId, list);
        }
    }
    return list;
}
 
Example 5
Source Project: actframework   File: EventBus.java    License: Apache License 2.0 5 votes vote down vote up
private EventBus _bind(ConcurrentMap<Key, List<SimpleEventListener>> listeners, Key key, final SimpleEventListener eventListener) {
    List<SimpleEventListener> list = listeners.get(key);
    if (null == list) {
        List<SimpleEventListener> newList = new ArrayList<>();
        list = listeners.putIfAbsent(key, newList);
        if (null == list) {
            list = newList;
        }
    }
    addIntoListWithOrder(list, eventListener);
    return this;
}
 
Example 6
private   void checkMigrateRule(String schemal,RouteResultset rrs,int sqlType ) throws SQLNonTransientException {
	if(rrs!=null&&rrs.getTables()!=null){
		boolean isUpdate=isUpdateSql(sqlType);
		if(!isUpdate)return;
		ConcurrentMap<String,List<PartitionByCRC32PreSlot.Range>> tableRules= RouteCheckRule.migrateRuleMap.get(schemal.toUpperCase()) ;
		if(tableRules!=null){
		for (String table : rrs.getTables()) {
			List<PartitionByCRC32PreSlot.Range> rangeList= tableRules.get(table.toUpperCase()) ;
			if(rangeList!=null&&!rangeList.isEmpty()){
				if(rrs.getNodes().length>1&&isUpdate){
					throw new   SQLNonTransientException ("schema:"+schemal+",table:"+table+",sql:"+rrs.getStatement()+" is not allowed,because table is migrate switching,please wait for a moment");
				}
				for (PartitionByCRC32PreSlot.Range range : rangeList) {
					RouteResultsetNode[] routeResultsetNodes=	rrs.getNodes();
					for (RouteResultsetNode routeResultsetNode : routeResultsetNodes) {
						int slot=routeResultsetNode.getSlot();
						if(isUpdate&&slot>=range.start&&slot<=range.end){
							throw new   SQLNonTransientException ("schema:"+schemal+",table:"+table+",sql:"+rrs.getStatement()+" is not allowed,because table is migrate switching,please wait for a moment");

						}
					}
				}
			}
		}
		}
	}
}
 
Example 7
Source Project: java-control-plane   File: SimpleCache.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected void respondWithSpecificOrder(T group, Snapshot snapshot,
                                        ConcurrentMap<String, CacheStatusInfo<T>> statusMap) {
  for (String typeUrl : Resources.TYPE_URLS) {
    CacheStatusInfo<T> status = statusMap.get(typeUrl);
    if (status == null) {
      continue;
    }

    status.watchesRemoveIf((id, watch) -> {
      if (!watch.request().getTypeUrl().equals(typeUrl)) {
        return false;
      }
      String version = snapshot.version(watch.request().getTypeUrl(), watch.request().getResourceNamesList());

      if (!watch.request().getVersionInfo().equals(version)) {
        if (LOGGER.isDebugEnabled()) {
          LOGGER.debug("responding to open watch {}[{}] with new version {}",
              id,
              String.join(", ", watch.request().getResourceNamesList()),
              version);
        }

        respond(watch, snapshot, group);

        // Discard the watch. A new watch will be created for future snapshots once envoy ACKs the response.
        return true;
      }

      // Do not discard the watch. The request version is the same as the snapshot version, so we wait to respond.
      return false;
    });
  }
}
 
Example 8
/**
 * Construct a Strategy that parses a Text field
 * @param locale The Locale of the TimeZone to parse
 * @param field The Calendar field
 * @param definingCalendar The calendar to obtain the short and long values
 * @return a TextStrategy for the field and Locale
 */
private Strategy getLocaleSpecificStrategy(int field, Calendar definingCalendar) {
	ConcurrentMap<Locale,Strategy> cache = getCache(field);
	Strategy strategy= cache.get(Integer.valueOf(field));
    if(strategy==null) {
    	strategy= field==Calendar.ZONE_OFFSET
    			? new TimeZoneStrategy(locale)
    			: new TextStrategy(field, definingCalendar, locale);
        Strategy inCache= cache.putIfAbsent(locale, strategy);
        if(inCache!=null) {
            return inCache;
        }
    }
    return strategy;
}
 
Example 9
Source Project: dubbo-2.6.5   File: RpcStatus.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param url
 * @param methodName
 * @return status
 */
public static RpcStatus getStatus(URL url, String methodName) {
    String uri = url.toIdentityString();
    ConcurrentMap<String, RpcStatus> map = METHOD_STATISTICS.get(uri);
    if (map == null) {
        METHOD_STATISTICS.putIfAbsent(uri, new ConcurrentHashMap<String, RpcStatus>());
        map = METHOD_STATISTICS.get(uri);
    }
    RpcStatus status = map.get(methodName);
    if (status == null) {
        map.putIfAbsent(methodName, new RpcStatus());
        status = map.get(methodName);
    }
    return status;
}
 
Example 10
Source Project: helix   File: StateModelFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * NOTE: This method is deprecated. Bring it back to keep backward compatible.
 * Replaced by StateModelFactory#getStateModel(String resourceName, String partitionKey)
 * Get the state model for a partition
 * @param partitionName
 * @return state model if exists, null otherwise
 */
@Deprecated
public T getStateModel(String partitionName) {
  // return the first state model that match partitionName
  // assuming partitionName is unique across all resources
  for (ConcurrentMap<String, T> map : _stateModelMap.values()) {
    if (map.containsKey(partitionName)) {
      return map.get(partitionName);
    }
  }
  return null;
}
 
Example 11
Source Project: dubbo3   File: RpcStatus.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param url        url
 * @param methodName method name
 * @return status
 */
public static RpcStatus getStatus(URL url, String methodName) {
    String uri = url.toIdentityString();
    ConcurrentMap<String, RpcStatus> map = METHOD_STATISTICS.get(uri);
    if (map == null) {
        METHOD_STATISTICS.putIfAbsent(uri, new ConcurrentHashMap<>());
        map = METHOD_STATISTICS.get(uri);
    }
    RpcStatus status = map.get(methodName);
    if (status == null) {
        map.putIfAbsent(methodName, new RpcStatus());
        status = map.get(methodName);
    }
    return status;
}
 
Example 12
protected V get(String entityName, EntityCondition condition, K key) {
    ConcurrentMap<K, V> conditionCache = getConditionCache(entityName, condition);
    if (conditionCache == null) {
        return null;
    }
    return conditionCache.get(key);
}
 
Example 13
Source Project: dubbox   File: RpcStatus.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param url
 * @param methodName
 * @return status
 */
public static RpcStatus getStatus(URL url, String methodName) {
    String uri = url.toIdentityString();
    ConcurrentMap<String, RpcStatus> map = METHOD_STATISTICS.get(uri);
    if (map == null) {
        METHOD_STATISTICS.putIfAbsent(uri, new ConcurrentHashMap<String, RpcStatus>());
        map = METHOD_STATISTICS.get(uri);
    }
    RpcStatus status = map.get(methodName);
    if (status == null) {
        map.putIfAbsent(methodName, new RpcStatus());
        status = map.get(methodName);
    }
    return status;
}
 
Example 14
Source Project: everrest   File: ProviderBinder.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private <K, PF extends ObjectModel> void addProviderFactory(ConcurrentMap<K, List<ObjectFactory<PF>>> providersFactoryMap,
                                                            K key,
                                                            ObjectFactory<PF> providerFactory) {
    List<ObjectFactory<PF>> providersFactoryList = providersFactoryMap.get(key);
    if (providersFactoryList == null) {
        List<ObjectFactory<PF>> newList = new CopyOnWriteArrayList<>();
        providersFactoryList = providersFactoryMap.putIfAbsent(key, newList);
        if (providersFactoryList == null) {
            providersFactoryList = newList;
        }
    }
    providersFactoryList.add(providerFactory);
}
 
Example 15
Source Project: consulo   File: TemplateManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
private static OffsetsInFile insertDummyIdentifierWithCache(PsiFile file, int startOffset, int endOffset, String replacement) {
  ProperTextRange editRange = ProperTextRange.create(startOffset, endOffset);
  assertRangeWithinDocument(editRange, file.getViewProvider().getDocument());

  ConcurrentMap<Pair<ProperTextRange, String>, OffsetsInFile> map = CachedValuesManager.getCachedValue(file, () -> CachedValueProvider.Result
          .create(ConcurrentFactoryMap.createMap(key -> copyWithDummyIdentifier(new OffsetsInFile(file), key.first.getStartOffset(), key.first.getEndOffset(), key.second)), file,
                  file.getViewProvider().getDocument()));
  return map.get(Pair.create(editRange, replacement));
}
 
Example 16
Source Project: anno4j   File: RoleMatcher.java    License: Apache License 2.0 5 votes vote down vote up
private void add(ConcurrentMap<String, Collection<Class<?>>> map,
		String pattern, Class<?> role) {
	Collection<Class<?>> list = map.get(pattern);
	if (list == null) {
		list = new CopyOnWriteArrayList<Class<?>>();
		Collection<Class<?>> o = map.putIfAbsent(pattern, list);
		if (o != null) {
			list = o;
		}
	}
	if (!list.contains(role)) {
		list.add(role);
	}
}
 
Example 17
/**
 * Returns a LocaleProviderAdapter for the given locale service provider that
 * best matches the given locale. This method returns the LocaleProviderAdapter
 * for JRE if none is found for the given locale.
 *
 * @param providerClass the class for the locale service provider
 * @param locale the desired locale.
 * @return a LocaleProviderAdapter
 */
public static LocaleProviderAdapter getAdapter(Class<? extends LocaleServiceProvider> providerClass,
                                           Locale locale) {
    LocaleProviderAdapter adapter;

    // cache lookup
    ConcurrentMap<Locale, LocaleProviderAdapter> adapterMap = adapterCache.get(providerClass);
    if (adapterMap != null) {
        if ((adapter = adapterMap.get(locale)) != null) {
            return adapter;
        }
    } else {
        adapterMap = new ConcurrentHashMap<>();
        adapterCache.putIfAbsent(providerClass, adapterMap);
    }

    // Fast look-up for the given locale
    adapter = findAdapter(providerClass, locale);
    if (adapter != null) {
        adapterMap.putIfAbsent(locale, adapter);
        return adapter;
    }

    // Try finding an adapter in the normal candidate locales path of the given locale.
    List<Locale> lookupLocales = ResourceBundle.Control.getControl(ResourceBundle.Control.FORMAT_DEFAULT)
                                    .getCandidateLocales("", locale);
    for (Locale loc : lookupLocales) {
        if (loc.equals(locale)) {
            // We've already done with this loc.
            continue;
        }
        adapter = findAdapter(providerClass, loc);
        if (adapter != null) {
            adapterMap.putIfAbsent(locale, adapter);
            return adapter;
        }
    }

    // returns the adapter for FALLBACK as the last resort
    adapterMap.putIfAbsent(locale, fallbackLocaleProviderAdapter);
    return fallbackLocaleProviderAdapter;
}
 
Example 18
/**
 * 提交事务
 */
public void commit(final OkPacket packet, final BlockingSession session, final int initCount) {
    // 初始化
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        this.isFail.set(false);
        this.nodeCount = initCount;
        this.indicatedOK = packet;
    } finally {
        lock.unlock();
    }

    if (session.getSource().isClosed()) {
        decrementCountToZero();
        return;
    }

    // 执行
    final ConcurrentMap<RouteResultsetNode, Channel> target = session.getTarget();
    Executor executor = session.getSource().getProcessor().getExecutor();
    int started = 0;
    for (RouteResultsetNode rrn : target.keySet()) {
        if (rrn == null) {
            try {
                getLogger().error(
                        "null is contained in RoutResultsetNodes, source = " + session.getSource()
                                + ", bindChannel = " + target);
            } catch (Exception e) {
            }
            continue;
        }
        final MySQLChannel mc = (MySQLChannel) target.get(rrn);
        if (mc != null) {
            mc.setRunning(true);
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    _commit(mc, session);
                }
            });
            ++started;
        }
    }

    if (started < initCount && decrementCountBy(initCount - started)) {
        /**
         * assumption: only caused by front-end connection close. <br/>
         * Otherwise, packet must be returned to front-end
         */
        session.clear();
    }
}
 
Example 19
/**
 * Look-up the value through the cache. This always evaluates the
 * {@code subKeyFactory} function and optionally evaluates
 * {@code valueFactory} function if there is no entry in the cache for given
 * pair of (key, subKey) or the entry has already been cleared.
 *
 * @param key       possibly null key
 * @param parameter parameter used together with key to create sub-key and
 *                  value (should not be null)
 * @return the cached value (never null)
 * @throws NullPointerException if {@code parameter} passed in or
 *                              {@code sub-key} calculated by
 *                              {@code subKeyFactory} or {@code value}
 *                              calculated by {@code valueFactory} is null.
 */
public V get(K key, P parameter) {
    Objects.requireNonNull(parameter);

    expungeStaleEntries();

    Object cacheKey = CacheKey.valueOf(key, refQueue);

    // lazily install the 2nd level valuesMap for the particular cacheKey
    ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
    if (valuesMap == null) {
        ConcurrentMap<Object, Supplier<V>> oldValuesMap
            = map.putIfAbsent(cacheKey,
                              valuesMap = new ConcurrentHashMap<>());
        if (oldValuesMap != null) {
            valuesMap = oldValuesMap;
        }
    }

    // create subKey and retrieve the possible Supplier<V> stored by that
    // subKey from valuesMap
    Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
    Supplier<V> supplier = valuesMap.get(subKey);
    Factory factory = null;

    while (true) {
        if (supplier != null) {
            // supplier might be a Factory or a CacheValue<V> instance
            V value = supplier.get();
            if (value != null) {
                return value;
            }
        }
        // else no supplier in cache
        // or a supplier that returned null (could be a cleared CacheValue
        // or a Factory that wasn't successful in installing the CacheValue)

        // lazily construct a Factory
        if (factory == null) {
            factory = new Factory(key, parameter, subKey, valuesMap);
        }

        if (supplier == null) {
            supplier = valuesMap.putIfAbsent(subKey, factory);
            if (supplier == null) {
                // successfully installed Factory
                supplier = factory;
            }
            // else retry with winning supplier
        } else {
            if (valuesMap.replace(subKey, supplier, factory)) {
                // successfully replaced
                // cleared CacheEntry / unsuccessful Factory
                // with our Factory
                supplier = factory;
            } else {
                // retry with current supplier
                supplier = valuesMap.get(subKey);
            }
        }
    }
}
 
Example 20
Source Project: neural   File: Router.java    License: MIT License 2 votes vote down vote up
/**
 * 第一步:根据ID查找该用户的特征属性集
 *
 * @param consumerId
 * @param categories
 * @return
 */
private ConcurrentMap<String, String> selectCategories(
        String consumerId, ConcurrentMap<String, ConcurrentMap<String, String>> categories) {
    return categories.get(consumerId);
}