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

The following examples show how to use java.util.concurrent.ConcurrentMap#putAll() . 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 File: CacheFixedVersionConsumerServiceImpl.java    From qconfig with MIT License 6 votes vote down vote up
private void refreshCache() {
    Stopwatch stopwatch = Stopwatch.createStarted();
    logger.info("start refreshing fixed version consumer cache");
    try {
        ConcurrentMap<MetaIp, Long> newCache = Maps.newConcurrentMap();
        synchronized (this) {
            newCache.putAll(fixedConsumerVersionDao.queryAll());
            cache = newCache;
        }
        logger.info("refreshing fixed version consumer cache successOf, total num:[{}]", newCache.size());
    } catch (Exception e) {
        logger.error("refreshing fixed version consumer cache error", e);
    } finally {
        Monitor.freshFixedVersionConsumerCache.update(stopwatch.elapsed().toMillis(), TimeUnit.MILLISECONDS);
    }
}
 
Example 2
Source File: ServiceLoader.java    From beihu-boot with Apache License 2.0 5 votes vote down vote up
public static Set<String> getServiceProviders(final Class<?> clazz) {

        if (clazz == null)
            throw new IllegalArgumentException("type == null");
        if (!clazz.isInterface()) {
            throw new IllegalArgumentException(" type(" + clazz + ") is not interface!");
        }
        if (!clazz.isAnnotationPresent(SPI.class)) {
            throw new IllegalArgumentException("type(" + clazz +
                    ") is not extension, because WITHOUT @" + SPI.class.getSimpleName() + " Annotation!");
        }

        SPI spi = clazz.getAnnotation(SPI.class);
        String defaultName = spi.dftValue();
        String dynamicConfigKey = spi.key();


        final Set<URLDefinition> urlDefinitions = new HashSet<URLDefinition>();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        urlDefinitions.addAll(collectExtensionUrls(LTS_DIRECTORY + clazz.getName(), classLoader));
        urlDefinitions.addAll(collectExtensionUrls(LTS_INTERNAL_DIRECTORY + clazz.getName(), classLoader));

        final ConcurrentMap<String, ServiceDefinition> serviceDefinitions = new ConcurrentHashMap<String, ServiceDefinition>();
        for (URLDefinition urlDefinition : urlDefinitions) {
            serviceDefinitions.putAll(parse(urlDefinition));
        }
        if (serviceDefinitions.isEmpty()) {
            throw new IllegalStateException("Service loader could not load " + clazz.getName() + "'s ServiceProvider from '" + LTS_DIRECTORY + "' or '" + LTS_INTERNAL_DIRECTORY + "' It may be empty or does not exist.");
        }
        ServiceProvider serviceProvider = new ServiceProvider(clazz, dynamicConfigKey, defaultName, serviceDefinitions);
        serviceMap.remove(clazz);   // 先移除
        serviceMap.put(clazz, serviceProvider);
        return serviceDefinitions.keySet();
    }
 
Example 3
Source File: BrowserUpProxyServer.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
@Override
public void addHeaders(Map<String, String> headers) {
    ConcurrentMap<String, String> newHeaders = new MapMaker().concurrencyLevel(1).makeMap();
    newHeaders.putAll(headers);

    this.additionalHeaders = newHeaders;
}
 
Example 4
Source File: BrowserMobProxyServer.java    From CapturePacket with MIT License 5 votes vote down vote up
@Override
public void addHeaders(Map<String, String> headers) {
    ConcurrentMap<String, String> newHeaders = new MapMaker().concurrencyLevel(1).makeMap();
    newHeaders.putAll(headers);

    this.additionalHeaders = newHeaders;
}
 
Example 5
Source File: QueryIndex.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Remove unused queries from the query cache.
 * <p>
 * This is normally called from a background thread at a rate set by configurePurgeFrequency().
 *
 * @throws IOException on IO errors
 */
private synchronized void purgeCache(CachePopulator populator) throws IOException {

  // Note on implementation

  // The purge works by scanning the query index and creating a new query cache populated
  // for each query in the index.  When the scan is complete, the old query cache is swapped
  // for the new, allowing it to be garbage-collected.

  // In order to not drop cached queries that have been added while a purge is ongoing,
  // we use a ReadWriteLock to guard the creation and removal of an register log.  Commits take
  // the read lock.  If the register log has been created, then a purge is ongoing, and queries
  // are added to the register log within the read lock guard.

  // The purge takes the write lock when creating the register log, and then when swapping out
  // the old query cache.  Within the second write lock guard, the contents of the register log
  // are added to the new query cache, and the register log itself is removed.

  final ConcurrentMap<String, QueryCacheEntry> newCache = new ConcurrentHashMap<>();

  purgeLock.writeLock().lock();
  try {
    purgeCache = new ConcurrentHashMap<>();
  } finally {
    purgeLock.writeLock().unlock();
  }

  populator.populateCacheWithIndex(newCache);

  purgeLock.writeLock().lock();
  try {
    newCache.putAll(purgeCache);
    purgeCache = null;
    queries = newCache;
  } finally {
    purgeLock.writeLock().unlock();
  }
}
 
Example 6
Source File: BrowserMobProxyServer.java    From Dream-Catcher with MIT License 5 votes vote down vote up
@Override
public void addHeaders(Map<String, String> headers) {
    ConcurrentMap<String, String> newHeaders = new MapMaker().concurrencyLevel(1).makeMap();
    newHeaders.putAll(headers);

    this.additionalHeaders = newHeaders;
}
 
Example 7
Source File: BrowserMobProxyServer.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
@Override
public void addHeaders(Map<String, String> headers) {
    ConcurrentMap<String, String> newHeaders = new MapMaker().concurrencyLevel(1).makeMap();
    newHeaders.putAll(headers);

    this.additionalHeaders = newHeaders;
}
 
Example 8
Source File: WebSocketConnectionRegistry.java    From actframework with Apache License 2.0 5 votes vote down vote up
/**
 * Sign in a group of connections to the registry by key
 *
 * @param key
 *         the key
 * @param connections
 *         a collection of websocket connections
 */
public void signIn(String key, Collection<WebSocketConnection> connections) {
    if (connections.isEmpty()) {
        return;
    }
    Map<WebSocketConnection, WebSocketConnection> newMap = new HashMap<>();
    for (WebSocketConnection conn : connections) {
        newMap.put(conn, conn);
    }
    ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key);
    bag.putAll(newMap);
}
 
Example 9
Source File: PartitionParser.java    From siddhi with Apache License 2.0 5 votes vote down vote up
public static PartitionRuntimeImpl parse(SiddhiAppRuntimeBuilder siddhiAppRuntimeBuilder, Partition partition,
                                         SiddhiAppContext siddhiAppContext, int queryIndex, int partitionIndex) {
    ConcurrentMap<String, AbstractDefinition> streamDefinitionMap =
            siddhiAppRuntimeBuilder.getStreamDefinitionMap();
    ConcurrentMap<String, AbstractDefinition> windowDefinitionMap =
            siddhiAppRuntimeBuilder.getWindowDefinitionMap();
    validateStreamPartitions(partition.getPartitionTypeMap(), streamDefinitionMap, windowDefinitionMap);
    PartitionRuntimeImpl partitionRuntime = new PartitionRuntimeImpl(streamDefinitionMap, windowDefinitionMap,
            siddhiAppRuntimeBuilder.getStreamJunctions(), partition, partitionIndex, siddhiAppContext);
    for (Query query : partition.getQueryList()) {
        List<VariableExpressionExecutor> executors = new ArrayList<VariableExpressionExecutor>();
        ConcurrentMap<String, AbstractDefinition> combinedStreamMap =
                new ConcurrentHashMap<String, AbstractDefinition>();
        combinedStreamMap.putAll(streamDefinitionMap);
        combinedStreamMap.putAll(windowDefinitionMap);
        combinedStreamMap.putAll(partitionRuntime.getLocalStreamDefinitionMap());
        QueryRuntimeImpl queryRuntime = QueryParser.parse(query, siddhiAppContext, combinedStreamMap,
                siddhiAppRuntimeBuilder.getTableDefinitionMap(),
                siddhiAppRuntimeBuilder.getWindowDefinitionMap(),
                siddhiAppRuntimeBuilder.getAggregationDefinitionMap(),
                siddhiAppRuntimeBuilder.getTableMap(),
                siddhiAppRuntimeBuilder.getAggregationMap(),
                siddhiAppRuntimeBuilder.getWindowMap(),
                siddhiAppRuntimeBuilder.getLockSynchronizer(),
                String.valueOf(queryIndex), true, partitionRuntime.getPartitionName());
        queryIndex++;
        MetaStateEvent metaStateEvent = createMetaEventForPartitioner(queryRuntime.getMetaComplexEvent());
        partitionRuntime.addQuery(queryRuntime);
        partitionRuntime.addPartitionReceiver(queryRuntime, executors, metaStateEvent);
        QueryParserHelper.reduceMetaComplexEvent(metaStateEvent);
        if (queryRuntime.getMetaComplexEvent() instanceof MetaStateEvent) {
            QueryParserHelper.updateVariablePosition(metaStateEvent, executors);
        } else {
            QueryParserHelper.updateVariablePosition(metaStateEvent.getMetaStreamEvent(0), executors);
        }
    }
    partitionRuntime.init();
    return partitionRuntime;

}
 
Example 10
Source File: ServiceLoader.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
public static Set<String> getServiceProviders(final Class<?> clazz) {

        if (clazz == null)
            throw new IllegalArgumentException("type == null");
        if (!clazz.isInterface()) {
            throw new IllegalArgumentException(" type(" + clazz + ") is not interface!");
        }
        if (!clazz.isAnnotationPresent(SPI.class)) {
            throw new IllegalArgumentException("type(" + clazz +
                    ") is not extension, because WITHOUT @" + SPI.class.getSimpleName() + " Annotation!");
        }

        SPI spi = clazz.getAnnotation(SPI.class);
        String defaultName = spi.dftValue();
        String dynamicConfigKey = spi.key();


        final Set<URLDefinition> urlDefinitions = new HashSet<URLDefinition>();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        urlDefinitions.addAll(collectExtensionUrls(LTS_DIRECTORY + clazz.getName(), classLoader));
        urlDefinitions.addAll(collectExtensionUrls(LTS_INTERNAL_DIRECTORY + clazz.getName(), classLoader));

        final ConcurrentMap<String, ServiceDefinition> serviceDefinitions = new ConcurrentHashMap<String, ServiceDefinition>();
        for (URLDefinition urlDefinition : urlDefinitions) {
            serviceDefinitions.putAll(parse(urlDefinition));
        }
        if (serviceDefinitions.isEmpty()) {
            throw new IllegalStateException("Service loader could not load " + clazz.getName() + "'s ServiceProvider from '" + LTS_DIRECTORY + "' or '" + LTS_INTERNAL_DIRECTORY + "' It may be empty or does not exist.");
        }
        ServiceProvider serviceProvider = new ServiceProvider(clazz, dynamicConfigKey, defaultName, serviceDefinitions);
        serviceMap.remove(clazz);   // 先移除
        serviceMap.put(clazz, serviceProvider);
        return serviceDefinitions.keySet();
    }
 
Example 11
Source File: RoundRobinLoadBalance.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
@Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
//        group/interface:version+方法名
        String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
//        先从缓存中获取
        ConcurrentMap<String, WeightedRoundRobin> map = methodWeightMap.get(key);
        if (map == null) {
            methodWeightMap.putIfAbsent(key, new ConcurrentHashMap<String, WeightedRoundRobin>());
            map = methodWeightMap.get(key);
        }
        int totalWeight = 0;
        long maxCurrent = Long.MIN_VALUE;
        long now = System.currentTimeMillis();
        Invoker<T> selectedInvoker = null;
        WeightedRoundRobin selectedWRR = null;
        for (Invoker<T> invoker : invokers) {
            String identifyString = invoker.getUrl().toIdentityString();
            WeightedRoundRobin weightedRoundRobin = map.get(identifyString);
//            查询权重
            int weight = getWeight(invoker, invocation);
            if (weight < 0) {
                weight = 0;
            }
            if (weightedRoundRobin == null) {
                weightedRoundRobin = new WeightedRoundRobin();
                weightedRoundRobin.setWeight(weight);
                map.putIfAbsent(identifyString, weightedRoundRobin);
                weightedRoundRobin = map.get(identifyString);
            }
            if (weight != weightedRoundRobin.getWeight()) {
                //weight changed
                weightedRoundRobin.setWeight(weight);
            }
            long cur = weightedRoundRobin.increaseCurrent();
            weightedRoundRobin.setLastUpdate(now);
            if (cur > maxCurrent) {
                maxCurrent = cur;
                selectedInvoker = invoker;
                selectedWRR = weightedRoundRobin;
            }
            totalWeight += weight;
        }
        if (!updateLock.get() && invokers.size() != map.size()) {
//            自旋锁的运用
            if (updateLock.compareAndSet(false, true)) {
                try {
                    // copy -> modify -> update reference
                    ConcurrentMap<String, WeightedRoundRobin> newMap = new ConcurrentHashMap<String, WeightedRoundRobin>();
                    newMap.putAll(map);
                    Iterator<Entry<String, WeightedRoundRobin>> it = newMap.entrySet().iterator();
                    while (it.hasNext()) {
                        Entry<String, WeightedRoundRobin> item = it.next();
                        if (now - item.getValue().getLastUpdate() > RECYCLE_PERIOD) {
                            it.remove();
                        }
                    }
                    methodWeightMap.put(key, newMap);
                } finally {
//                    finally中赋值,否则异常可能会导致锁没释放
                    updateLock.set(false);
                }
            }
        }
        if (selectedInvoker != null) {
            selectedWRR.sel(totalWeight);
            return selectedInvoker;
        }
        // should not happen here
        return invokers.get(0);
    }
 
Example 12
Source File: LocalLoadingCacheTest.java    From caffeine with Apache License 2.0 4 votes vote down vote up
public void testAsMap() {
  Caffeine<Object, Object> builder = createCacheBuilder();
  LoadingCache<Object, Object> cache = makeCache(builder, identityLoader());
  assertEquals(EMPTY_STATS, cache.stats());

  Object one = new Object();
  Object two = new Object();
  Object three = new Object();

  ConcurrentMap<Object, Object> map = cache.asMap();
  assertNull(map.put(one, two));
  assertSame(two, map.get(one));
  map.putAll(ImmutableMap.of(two, three));
  assertSame(three, map.get(two));
  assertSame(two, map.putIfAbsent(one, three));
  assertSame(two, map.get(one));
  assertNull(map.putIfAbsent(three, one));
  assertSame(one, map.get(three));
  assertSame(two, map.replace(one, three));
  assertSame(three, map.get(one));
  assertFalse(map.replace(one, two, three));
  assertSame(three, map.get(one));
  assertTrue(map.replace(one, three, two));
  assertSame(two, map.get(one));
  assertEquals(3, map.size());

  map.clear();
  assertTrue(map.isEmpty());
  assertEquals(0, map.size());

  cache.getUnchecked(one);
  assertEquals(1, map.size());
  assertSame(one, map.get(one));
  assertTrue(map.containsKey(one));
  assertTrue(map.containsValue(one));
  assertSame(one, map.remove(one));
  assertEquals(0, map.size());

  cache.getUnchecked(one);
  assertEquals(1, map.size());
  assertFalse(map.remove(one, two));
  assertTrue(map.remove(one, one));
  assertEquals(0, map.size());

  cache.getUnchecked(one);
  Map<Object, Object> newMap = ImmutableMap.of(one, one);
  assertEquals(newMap, map);
  assertEquals(newMap.entrySet(), map.entrySet());
  assertEquals(newMap.keySet(), map.keySet());
  Set<Object> expectedValues = ImmutableSet.of(one);
  Set<Object> actualValues = ImmutableSet.copyOf(map.values());
  assertEquals(expectedValues, actualValues);
}