Java 8 ConcurrentHashMap - top ranked examples from Open Source projects

These code examples were ranked by Codota’s semantic indexing as the best open source examples for Java 8 ConcurrentHashMap class.

This code example shows how to use the following methods:
package com.taobao.oceanbase.network; 
 
import java.net.SocketAddress; 
import java.util.concurrent.ConcurrentHashMap; 
import java.util.concurrent.ConcurrentMap; 
import java.util.concurrent.TimeUnit; 
import java.util.concurrent.locks.ReentrantLock; 
 
public abstract class SessionFactory { 
 
	private ConcurrentMap<SocketAddress, Session> cache = new ConcurrentHashMap<SocketAddress, Session>();
 
	private ReentrantLock lock = new ReentrantLock();
 
	public Session getSession(Server server, SocketAddress address,
			int timeout, TimeUnit unit) {
		Session session = cache.get(address);
		if (session != null)
			return session;
		lock.lock();

10
CodeRank
This code example shows how to use the following methods:
    public static <K, V> ConcurrentMap<K, V> newConcurrentMapWithAggressiveConcurrency() {
        return new ConcurrentHashMap<>(16, 0.75f, aggressiveConcurrencyLevel);
    } 
 
    public static <K, V> ConcurrentMap<K, V> newConcurrentMap() {
        return new ConcurrentHashMap<>();
    } 
 
    /** 
     * Creates a new CHM with an aggressive concurrency level, aimed at highly updateable long living maps. 
     */ 
    public static <V> ConcurrentMapLong<V> newConcurrentMapLongWithAggressiveConcurrency() { 
        return new ConcurrentHashMapLong<>(ConcurrentCollections.<Long, V>newConcurrentMapWithAggressiveConcurrency());
    } 
 
    public static <V> ConcurrentMapLong<V> newConcurrentMapLong() { 
        return new ConcurrentHashMapLong<>(ConcurrentCollections.<Long, V>newConcurrentMap());
    } 
 
    public static <V> Set<V> newConcurrentSet() {
10
CodeRank
This code example shows how to use the following methods:get, putIfAbsent
 
    public void subscribe(final String topic, final String group, final int maxSize,
            final MessageListener messageListener, final ConsumerMessageFilter consumerMessageFilter)
                    throws MetaClientException { 
        final ConcurrentHashMap<String, SubscriberInfo> topicSubsriberRegistry = this.getTopicSubscriberRegistry(group);
        SubscriberInfo info = topicSubsriberRegistry.get(topic);
        if (info == null) {
            info = new SubscriberInfo(messageListener, consumerMessageFilter, maxSize);
            final SubscriberInfo oldInfo = topicSubsriberRegistry.putIfAbsent(topic, info);
            if (oldInfo != null) {
                throw new MetaClientException("Topic=" + topic + " has been subscribered by group " + group);
            } 
        } 
        else { 
            throw new MetaClientException("Topic=" + topic + " has been subscribered by group " + group);
        } 
    } 
 
 
    private ConcurrentHashMap<String, SubscriberInfo> getTopicSubscriberRegistry(final String group)

9
CodeRank
This code example shows how to use the following methods:
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
 
public final class MockInternalEngine extends InternalEngine implements Engine { 
    public static final ConcurrentMap<AssertingSearcher, RuntimeException> INFLIGHT_ENGINE_SEARCHERS = new ConcurrentHashMap<>();
    public static final String WRAP_READER_RATIO = "index.engine.mock.random.wrap_reader_ratio";
    public static final String READER_WRAPPER_TYPE = "index.engine.mock.random.wrapper";
 
    private final Random random;
    private final boolean wrapReader;
    private final Class<? extends FilterDirectoryReader> wrapper;
 
    @Inject 
    public MockInternalEngine(ShardId shardId, @IndexSettings Settings indexSettings, ThreadPool threadPool,
                              IndexSettingsService indexSettingsService, ShardIndexingService indexingService, @Nullable IndicesWarmer warmer, Store store,
                              SnapshotDeletionPolicy deletionPolicy, Translog translog, MergePolicyProvider mergePolicyProvider,
                              MergeSchedulerProvider mergeScheduler, AnalysisService analysisService, SimilarityService similarityService,
                              CodecService codecService) throws EngineException {
        super(shardId, indexSettings, threadPool, indexSettingsService, indexingService, warmer, store,
10
CodeRank
This code example shows how to use the following methods:
    private boolean diskCacheEnabled = false;
    private ExecutorService writeThread;
 
    public WebImageCache(Context context) {
        // Set up in-memory cache store 
        memoryCache = new ConcurrentHashMap<String, SoftReference<Bitmap>>();
 
        // Set up disk cache store 
        Context appContext = context.getApplicationContext();
        diskCachePath = appContext.getCacheDir().getAbsolutePath() + DISK_CACHE_PATH;
 
        File outFile = new File(diskCachePath);
        outFile.mkdirs();
 
        diskCacheEnabled = outFile.exists();
 
        // Set up threadpool for image fetching tasks 
        writeThread = Executors.newSingleThreadExecutor();
    } 
 
10
CodeRank
This code example shows how to use the following methods:
  private Map<String, Object> contextData;
 
  @Override 
  public Map<String, Object> contextData() {
    if (contextData == null) { 
      contextData = new ConcurrentHashMap<>();
    } 
    return contextData; 
  } 
 
 
} 
10
CodeRank
This code example shows how to use the following methods:
 
import java.util.Map; 
import java.util.concurrent.ConcurrentHashMap; 
 
public class AddCustomRequestHeaderCommand extends Command { 
  private static Map<String, String> headers = new ConcurrentHashMap<String, String>();
 
  private String key;
  private String value;
 
  public AddCustomRequestHeaderCommand(String key, String value) {
    this.key = key;
    this.value = value;
  } 
 
  @Override 
  public String execute() {
    headers.put(key, value);
 
    return "OK"; 
10
CodeRank
This code example shows how to use the following methods:get, putIfAbsent
     * @return An instance of the AnnotationValidator. 
     * 
     * @since 4.12 
     */ 
    public AnnotationValidator createAnnotationValidator(ValidateWith validateWithAnnotation) {
        AnnotationValidator validator = VALIDATORS_FOR_ANNOTATION_TYPES.get(validateWithAnnotation);
        if (validator != null) {
            return validator;
        } 
 
        Class<? extends AnnotationValidator> clazz = validateWithAnnotation.value();
        if (clazz == null) {
            throw new IllegalArgumentException("Can't create validator, value is null in annotation " + validateWithAnnotation.getClass().getName());
        } 
        try { 
            AnnotationValidator annotationValidator = clazz.newInstance();
            VALIDATORS_FOR_ANNOTATION_TYPES.putIfAbsent(validateWithAnnotation, annotationValidator);
            return VALIDATORS_FOR_ANNOTATION_TYPES.get(validateWithAnnotation);
        } catch (Exception e) {
            throw new RuntimeException("Exception received when creating AnnotationValidator class " + clazz.getName(), e);

8
CodeRank
This code example shows how to use the following methods:get, putIfAbsent
    public <T> LocalLockMediator<T> get(String namespace, TimestampProvider times) { 
 
        Preconditions.checkNotNull(namespace); 
 
        @SuppressWarnings("unchecked") 
        LocalLockMediator<T> m = (LocalLockMediator<T>)mediators.get(namespace); 
 
        if (null == m) { 
            m = new LocalLockMediator<T>(namespace, times); 
            @SuppressWarnings("unchecked") 
            LocalLockMediator<T> old = (LocalLockMediator<T>)mediators.putIfAbsent(namespace, m); 
            if (null != old) 
                m = old; 
            else 
                log.debug("Local lock mediator instantiated for namespace {}", 
                        namespace); 
        } 
 
        return m; 
    } 
8
CodeRank
This code example shows how to use the following methods:
 
  public static final String LOGGER_DELEGATE_FACTORY_CLASS_NAME = "vertx.logger-delegate-factory-class-name";
 
  private static volatile LogDelegateFactory delegateFactory;
 
  private static final ConcurrentMap<String, Logger> loggers = new ConcurrentHashMap<>();
 
  static { 
    initialise(); 
  } 
 
  public static synchronized void initialise() { 
    LogDelegateFactory delegateFactory;
 
    // If a system property is specified then this overrides any delegate factory which is set 
    // programmatically - this is primarily of use so we can configure the logger delegate on the client side. 
    // call to System.getProperty is wrapped in a try block as it will fail if the client runs in a secured 
    // environment 
    String className = JULLogDelegateFactory.class.getName();
    try { 
10
CodeRank
This code example shows how to use the following methods:
package org.erlide.util.services; 
 
import java.util.Map; 
import java.util.concurrent.ConcurrentHashMap; 
 
import org.eclipse.xtext.xbase.lib.Pair; 
 
public class ServiceLocator { 
    private final static Map<Pair<Class<?>, Object>, Object> services = new ConcurrentHashMap<Pair<Class<?>, Object>, Object>();
    private final static Map<Pair<Class<?>, Object>, Provider<?>> providers = new ConcurrentHashMap<Pair<Class<?>, Object>, Provider<?>>();
 
    /** 
     * Acquire an implementation of a service, identified by id key. If one has 
     * not already been instantiated, instantiate the class defined by the 
     * Implementor annotation on the interface. If the implementor is an 
     * instance of Provider<T>, use it to instantiate the service. 
     */ 
    public static <T> T get(final Class<T> interfaceClass, final Object key) {
        synchronized (interfaceClass) {
            Object service = services

9
CodeRank
This code example shows how to use the following methods:get, putIfAbsent
    // String is ThreadPoolKey.name() (we can't use ThreadPoolKey directly as we can't guarantee it implements hashcode/equals correctly) 
    private final ConcurrentHashMap<String, HystrixMetricsPublisherThreadPool> threadPoolPublishers = new ConcurrentHashMap<String, HystrixMetricsPublisherThreadPool>();
 
    /* package */ HystrixMetricsPublisherThreadPool getPublisherForThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties) {
        // attempt to retrieve from cache first 
        HystrixMetricsPublisherThreadPool publisher = threadPoolPublishers.get(threadPoolKey.name());
        if (publisher != null) {
            return publisher;
        } 
        // it doesn't exist so we need to create it 
        publisher = strategy.getMetricsPublisherForThreadPool(threadPoolKey, metrics, properties);
        // attempt to store it (race other threads) 
        HystrixMetricsPublisherThreadPool existing = threadPoolPublishers.putIfAbsent(threadPoolKey.name(), publisher);
        if (existing == null) {
            // we won the thread-race to store the instance we created so initialize it 
            publisher.initialize();
            // done registering, return instance that got cached 
            return publisher;
        } else { 
            // we lost so return 'existing' and let the one we created be garbage collected 
8
CodeRank
This code example shows how to use the following methods:
 * @since 4.0 
 */ 
public class DefaultUserSessionRegistry implements UserSessionRegistry {
 
	// userId -> sessionId 
	private final ConcurrentMap<String, Set<String>> userSessionIds = new ConcurrentHashMap<String, Set<String>>();
 
	private final Object lock = new Object(); 
 
 
	@Override 
	public Set<String> getSessionIds(String user) {
		Set<String> set = this.userSessionIds.get(user);
		return (set != null) ? set : Collections.<String>emptySet();
	} 
 
	@Override 
	public void registerSessionId(String user, String sessionId) {
		Assert.notNull(user, "User must not be null");
		Assert.notNull(sessionId, "Session ID must not be null");
10
CodeRank
This code example shows how to use the following methods:
import java.util.concurrent.ConcurrentHashMap; 
 
import com.afforess.minecartmaniacore.world.Item; 
 
public class ItemAliasList{ 
	public static ConcurrentHashMap<String, List<Item>> aliases = new ConcurrentHashMap<String, List<Item>>();
	 
	public static boolean isAlias(String alias) {
		Iterator<Entry<String, List<Item>>> i = aliases.entrySet().iterator();
		while(i.hasNext()) {
			Entry<String, List<Item>> e = i.next();
			String key = e.getKey();
			if (key.equalsIgnoreCase(alias)) {
				return true; 
			} 
		} 
		return false; 
	} 
	 
	public static List<Item> getItemsForAlias(String alias) {
9
CodeRank
This code example shows how to use the following methods:get, putIfAbsent
     */ 
    public static HystrixThreadPoolProperties getThreadPoolProperties(HystrixThreadPoolKey key, HystrixThreadPoolProperties.Setter builder) { 
        HystrixPropertiesStrategy hystrixPropertiesStrategy = HystrixPlugins.getInstance().getPropertiesStrategy(); 
        String cacheKey = hystrixPropertiesStrategy.getThreadPoolPropertiesCacheKey(key, builder); 
        if (cacheKey != null) { 
            HystrixThreadPoolProperties properties = threadPoolProperties.get(cacheKey); 
            if (properties != null) { 
                return properties; 
            } else { 
                if (builder == null) { 
                    builder = HystrixThreadPoolProperties.Setter(); 
                } 
                // create new instance 
                properties = hystrixPropertiesStrategy.getThreadPoolProperties(key, builder); 
                // cache and return 
                HystrixThreadPoolProperties existing = threadPoolProperties.putIfAbsent(cacheKey, properties); 
                if (existing == null) { 
                    return properties; 
                } else { 
                    return existing; 
                } 
8
CodeRank
This code example shows how to use the following methods:
 * @author Rod Johnson 
 * @author Juergen Hoeller 
 */ 
public class ExpectedLookupTemplate extends JndiTemplate {
 
	private final Map<String, Object> jndiObjects = new ConcurrentHashMap<String, Object>();
 
 
	/** 
	 * Construct a new JndiTemplate that will always return given objects 
	 * for given names. To be populated through {@code addObject} calls. 
	 * @see #addObject(String, Object) 
	 */ 
	public ExpectedLookupTemplate() { 
	} 
 
	/** 
	 * Construct a new JndiTemplate that will always return the 
	 * given object, but honour only requests for the given name. 
	 * @param name the name the client is expected to look up 
10
CodeRank
This code example shows how to use the following methods:
class LocalMapImpl<K, V> implements LocalMap<K, V> { 
 
 
  private final ConcurrentMap<Object, LocalMap<?, ?>> maps;
  private final String name;
  private final ConcurrentMap<K, V> map = new ConcurrentHashMap<>();
 
  LocalMapImpl(String name, ConcurrentMap<Object, LocalMap<?, ?>> maps) {
    this.name = name;
    this.maps = maps;
  } 
 
  @Override 
  public V get(K key) {
    return copyIfRequired(map.get(key));
  } 
 
  @Override 
  public V put(K key, V value) {
    checkType(key);
10
CodeRank
This code example shows how to use the following methods:
public class AnnotationInstanceProvider { 
 
    private final ConcurrentMap<Class<?>, Class<?>> cache;
 
    public AnnotationInstanceProvider() { 
        cache = new ConcurrentHashMap<Class<?>, Class<?>>();
    } 
 
    /** 
     * <p> 
     * Returns an instance of the given annotation type with attribute values 
     * specified in the map. 
     * </p> 
     * <p/> 
     * <ul> 
     * <li> 
     * For {@link Annotation}, array and enum types the values must exactly match 
     * the declared return type of the attribute or a {@link ClassCastException} 
     * will result.</li> 
     * <p/> 
9
CodeRank
This code example shows how to use the following methods:
  public ConcurrentHashSet(int size) { 
    map = new ConcurrentHashMap<>(size); 
  } 
 
  public ConcurrentHashSet() { 
    map = new ConcurrentHashMap<>(); 
  } 
 
  @Override 
  public int size() { 
    return map.size(); 
  } 
 
  @Override 
  public boolean isEmpty() { 
    return map.isEmpty(); 
  } 
 
  @Override 
  public boolean contains(Object o) { 
10
CodeRank
This code example shows how to use the following methods:
 * @since 4.1 
 * @see DestinationResolver#resolveDestination 
 */ 
public class CachingDestinationResolverProxy<D> implements DestinationResolver<D>, InitializingBean {
 
	private final Map<String, D> resolvedDestinationCache = new ConcurrentHashMap<String, D>();
 
	private DestinationResolver<D> targetDestinationResolver;
 
 
	/** 
	 * Create a new CachingDestinationResolverProxy, setting the target DestinationResolver 
	 * through the {@link #setTargetDestinationResolver} bean property. 
	 */ 
	public CachingDestinationResolverProxy() { 
	} 
 
	/** 
	 * Create a new CachingDestinationResolverProxy using the given target 
	 * DestinationResolver to actually resolve destinations. 
10
CodeRank
This code example shows how to use the following methods:get, putIfAbsent
     *            Pass-thru to {@link HystrixThreadPoolMetrics} instance on first time when constructed 
     * @return {@link HystrixThreadPoolMetrics} 
     */ 
    public static HystrixThreadPoolMetrics getInstance(HystrixThreadPoolKey key, ThreadPoolExecutor threadPool, HystrixThreadPoolProperties properties) {
        // attempt to retrieve from cache first 
        HystrixThreadPoolMetrics threadPoolMetrics = metrics.get(key.name());
        if (threadPoolMetrics != null) {
            return threadPoolMetrics;
        } 
        // it doesn't exist so we need to create it 
        threadPoolMetrics = new HystrixThreadPoolMetrics(key, threadPool, properties);
        // attempt to store it (race other threads) 
        HystrixThreadPoolMetrics existing = metrics.putIfAbsent(key.name(), threadPoolMetrics);
        if (existing == null) {
            // we won the thread-race to store the instance we created 
            return threadPoolMetrics;
        } else { 
            // we lost so return 'existing' and let the one we created be garbage collected 
            return existing;
        } 
8
CodeRank
This code example shows how to use the following methods:
import java.util.Random; 
import java.util.concurrent.ConcurrentHashMap; 
 
public class DummyHandler implements UserPriviligesHandler { 
    private static String[] TIERS = {"bronze","silver","platinum"};
    public static Map apiKey2roleMap = new ConcurrentHashMap();
 
    public boolean authenticateUser(AuthenticationFuture callback) {
        callback.setAuthenticated(true);
        ArrayList roles = new ArrayList();
        Random rnd = new Random();
        if(apiKey2roleMap.get(callback.getAPIKey()) != null){
            roles.add(apiKey2roleMap.get(callback.getAPIKey()));
        }else{ 
            String role = TIERS[rnd.nextInt(TIERS.length)];
            apiKey2roleMap.put(callback.getAPIKey() ,role);
            roles.add(role);
        } 
 
        callback.setAuthorizedRoles(roles);
8
CodeRank
This code example shows how to use the following methods:
 
  @SuppressWarnings("unused") 
  private static final Logger log = LoggerFactory.getLogger(HandlerManager.class); 
 
  private final VertxEventLoopGroup availableWorkers;
  private final ConcurrentMap<EventLoop, Handlers<T>> handlerMap = new ConcurrentHashMap<>();
 
  // We maintain a separate hasHandlers variable so we can implement hasHandlers() efficiently 
  // As it is called for every HTTP message received 
  private volatile boolean hasHandlers;
 
  public HandlerManager(VertxEventLoopGroup availableWorkers) {
    this.availableWorkers = availableWorkers;
  } 
 
  public boolean hasHandlers() { 
    return hasHandlers;
  } 
 
  public HandlerHolder<T> chooseHandler(EventLoop worker) {
10
CodeRank
This code example shows how to use the following methods:
 
import java.util.concurrent.ConcurrentHashMap; 
 
public class ComputeData { 
 
    public static ConcurrentHashMap<Integer, ConcurrentHashMap<String, StatisticData>> map = new ConcurrentHashMap<Integer, ConcurrentHashMap<String, StatisticData>>();
 
    public /*synchronized*/ void setRequestData(StatisticData requestData) {
 
        if (map.containsKey(requestData.getTenantId())) {
            ConcurrentHashMap<String, StatisticData> m = map.get(requestData.getTenantId());
 
            if (m.containsKey(requestData.getWebappName())) {
                    StatisticData st = updateRequestsData(requestData, m.get(requestData.getWebappName()));
                    m.put(requestData.getWebappName(), st);
                    map.put(requestData.getTenantId(),m);
 
            } else { 
                m.put(requestData.getWebappName(), requestData);
                map.put(requestData.getTenantId(), m);
8
CodeRank
This code example shows how to use the following methods:
            throw new RuntimeException(e);
        } 
    } 
 
    private FESessionManager(){ 
        this.sessionMap = new ConcurrentHashMap<String, FESessionBean>();
    } 
 
    public static FESessionManager getInstance(){ 
        if(sessionManager == null){
            sessionManager = new FESessionManager();
        } 
        return sessionManager;
    } 
 
    /** 
     * Get the corresponding FESessionBean for a particular session id 
     * @param sessionID session id 
     * @return  FESessionBean 
     */ 
8
CodeRank
This code example shows how to use the following methods:
	protected Cache cache;
 
 
	@Before 
	public void setUp() throws Exception {
		nativeCache = new ConcurrentHashMap<Object, Object>();
		cache = new ConcurrentMapCache(CACHE_NAME, nativeCache, true);
		cache.clear();
	} 
 
 
	@Test
	public void testCacheName() throws Exception {
		assertEquals(CACHE_NAME, cache.getName());
	} 
 
	@Test
	public void testNativeCache() throws Exception {
		assertSame(nativeCache, cache.getNativeCache());
	} 
10
CodeRank
This code example shows how to use the following methods:
      this.timestamp = timestamp;
      this.username = username;
    } 
  } 
  private static final Map<Long, CachedUid> uidCache = 
    new ConcurrentHashMap<Long, CachedUid>();
  private static long cacheTimeout;
  private static boolean initialized = false;
   
  public static String getOwner(FileDescriptor fd) throws IOException {
    ensureInitialized(); 
    long uid = getUIDforFDOwnerforOwner(fd);
    CachedUid cUid = uidCache.get(uid);
    long now = System.currentTimeMillis();
    if (cUid != null && (cUid.timestamp + cacheTimeout) > now) {
      return cUid.username;
    } 
    String user = getUserName(uid);
    LOG.info("Got UserName " + user + " for UID " + uid + 
        " from the native implementation"); 
8
CodeRank
This code example shows how to use the following methods:
	private static final String NO_VALUE = ObjectUtils.identityToString(new Object());
 
	private static final Log logger = LogFactory.getLog(SpringConfigurator.class);
 
	private static final Map<String, Map<Class<?>, String>> cache =
			new ConcurrentHashMap<String, Map<Class<?>, String>>();
 
 
	@SuppressWarnings("unchecked") 
	@Override 
	public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
		WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
		if (wac == null) {
			String message = "Failed to find the root WebApplicationContext. Was ContextLoaderListener not used?";
			logger.error(message);
			throw new IllegalStateException(message);
		} 
 
		String beanName = ClassUtils.getShortNameAsProperty(endpointClass);
		if (wac.containsBean(beanName)) {
10
CodeRank
This code example shows how to use the following methods:
 
 
	private final BeanCreatingHandlerProvider<WebSocketHandler> provider;
 
	private final Map<WebSocketSession, WebSocketHandler> handlers =
			new ConcurrentHashMap<WebSocketSession, WebSocketHandler>();
 
	private final boolean supportsPartialMessages;
 
 
	public PerConnectionWebSocketHandler(Class<? extends WebSocketHandler> handlerType) {
		this(handlerType, false);
	} 
 
	public PerConnectionWebSocketHandler(Class<? extends WebSocketHandler> handlerType, boolean supportsPartialMessages) {
		this.provider = new BeanCreatingHandlerProvider<WebSocketHandler>(handlerType);
		this.supportsPartialMessages = supportsPartialMessages;
	} 
 
	@Override 
10
CodeRank
This code example shows how to use the following methods:
 
public class FactoryFinder { 
 
    private final String path;
 
    private final Map<String, Class<?>> classMap = new ConcurrentHashMap<String, Class<?>>();
 
    public FactoryFinder(String path) {
        this.path = path;
    } 
 
    /** 
     * Creates a new instance of the given key 
     * 
     * @param key is the key to add to the path to find a text file 
     *            containing the factory name 
     * @return a newly created instance 
     */ 
    public Object newInstance(String key) throws IllegalAccessException, InstantiationException, IOException,
            ClassNotFoundException { 
8
CodeRank
See Code Examples for Java 8 ConcurrentHashMap Methods: