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

The following examples show how to use java.util.concurrent.ConcurrentMap#putIfAbsent() . 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: perf_hash_test.java    From Jupiter with Apache License 2.0 6 votes vote down vote up
public int run_normal(ConcurrentMap<String, String> hm) {
    SimpleRandom R = new SimpleRandom();

    int get_ops = 0;
    int put_ops = 0;
    int del_ops = 0;
    while (!_stop) {
        int x = R.nextInt() & ((1 << 20) - 1);
        String key = KEYS[R.nextInt() & (KEYS.length - 1)];
        if (x < _gr) {
            get_ops++;
            String val = hm.get(key);
            if (val != null && !val.equals(key))
                throw new IllegalArgumentException("Mismatched key=" + key + " and val=" + val);
        } else if (x < _pr) {
            put_ops++;
            hm.putIfAbsent(key, key);
        } else {
            del_ops++;
            hm.remove(key);
        }
    }
    // We stopped; report results into shared result structure
    return get_ops + put_ops + del_ops;
}
 
Example 2
Source File: SubnetWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Changes hostRoutes JsonNode to a collection of the hostRoutes.
 *
 * @param hostRoutes the hostRoutes json node
 * @return a collection of hostRoutes
 */
public Iterable<HostRoute> jsonNodeToHostRoutes(JsonNode hostRoutes) {
    checkNotNull(hostRoutes, JSON_NOT_NULL);
    ConcurrentMap<Integer, HostRoute> hostRouteMaps = Maps
            .newConcurrentMap();
    Integer i = 0;
    for (JsonNode node : hostRoutes) {
        IpAddress nexthop = IpAddress.valueOf(node.get("nexthop").asText());
        IpPrefix destination = IpPrefix.valueOf(node.get("destination")
                .asText());
        HostRoute hostRoute = new DefaultHostRoute(nexthop, destination);
        hostRouteMaps.putIfAbsent(i, hostRoute);
        i++;
    }
    return Collections.unmodifiableCollection(hostRouteMaps.values());
}
 
Example 3
Source File: BlurControllerServer.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
private void watchTables(final String cluster, ConcurrentMap<String, WatchChildren> map) {
  String path = ZookeeperPathConstants.getTablesPath(cluster);
  if (map.containsKey(cluster)) {
    return;
  }
  WatchChildren watchForTableLayoutChanges = new WatchChildren(_zookeeper, path);
  watchForTableLayoutChanges.watch(new OnChange() {
    @Override
    public void action(List<String> children) {
      LOG.info("Layout change for cluster [{0}].", cluster);
      updateLayout(cluster);
    }
  });
  if (map.putIfAbsent(cluster, watchForTableLayoutChanges) != null) {
    watchForTableLayoutChanges.close();
  }
}
 
Example 4
Source File: DefaultMessageStore.java    From rocketmq-read with Apache License 2.0 5 votes vote down vote up
/**
 * 找到消费队列
 * @param topic topic
 * @param queueId 队列id
 * @return ;
 */
public ConsumeQueue findConsumeQueue(String topic, int queueId) {
    ConcurrentMap<Integer, ConsumeQueue> map = consumeQueueTable.get(topic);
    if (null == map) {
        ConcurrentMap<Integer, ConsumeQueue> newMap = new ConcurrentHashMap<Integer, ConsumeQueue>(128);
        ConcurrentMap<Integer, ConsumeQueue> oldMap = consumeQueueTable.putIfAbsent(topic, newMap);
        if (oldMap != null) {
            map = oldMap;
        } else {
            map = newMap;
        }
    }

    //根据队列id获取逻辑队列
    ConsumeQueue logic = map.get(queueId);
    if (null == logic) {
        //构造逻辑队列
        ConsumeQueue newLogic = new ConsumeQueue(
            topic,
            queueId,
            StorePathConfigHelper.getStorePathConsumeQueue(this.messageStoreConfig.getStorePathRootDir()),
            this.getMessageStoreConfig().getMapedFileSizeConsumeQueue(),
            this);
        ConsumeQueue oldLogic = map.putIfAbsent(queueId, newLogic);
        if (oldLogic != null) {
            logic = oldLogic;
        } else {
            logic = newLogic;
        }
    }

    return logic;
}
 
Example 5
Source File: SequenceIdAccounting.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * We've been passed a new sequenceid for the region. Set it as highest seen for this region and
 * if we are to record oldest, or lowest sequenceids, save it as oldest seen if nothing
 * currently older.
 * @param encodedRegionName
 * @param families
 * @param sequenceid
 * @param lowest Whether to keep running account of oldest sequence id.
 */
void update(byte[] encodedRegionName, Set<byte[]> families, long sequenceid,
    final boolean lowest) {
  Long l = Long.valueOf(sequenceid);
  this.highestSequenceIds.put(encodedRegionName, l);
  if (lowest) {
    ConcurrentMap<ImmutableByteArray, Long> m = getOrCreateLowestSequenceIds(encodedRegionName);
    for (byte[] familyName : families) {
      m.putIfAbsent(ImmutableByteArray.wrap(familyName), l);
    }
  }
}
 
Example 6
Source File: ChainBuildingMessageHandler.java    From protect with MIT License 5 votes vote down vote up
private synchronized void recordVote(final long messagePosition, final SignedMessage bftMessage,
		final int voterId) {
	// Get the map for this position
	this.votes.putIfAbsent(messagePosition, new ConcurrentHashMap<SignedMessage, Set<Integer>>());
	final ConcurrentMap<SignedMessage, Set<Integer>> positionVotes = this.votes.get(messagePosition);

	// Get the set of votes for this message
	positionVotes.putIfAbsent(bftMessage, new ConcurrentSkipListSet<>());
	final Set<Integer> messageVotes = positionVotes.get(bftMessage);
	messageVotes.add(voterId);

	// Check if Opt-BFT quorum has been met
	if (messageVotes.size() == this.optQuorum) {
		// System.err.println("QUORUM MET, added " + (optChain.size() + 1) + "th message
		// to Opt-BFT Chain: " /*+ bftMessage*/);
		synchronized (this.optChain) {

			System.out.println("Certified message #" + (messagePosition + 1) + " is available.");
			if (this.optChain.putIfAbsent(messagePosition + 1, bftMessage) == null) {

				// Increment contiguousOptMessages if we are contiguous
				while (this.optChain.containsKey(new Long(contiguousOptMessages.get() + 1))) {
					contiguousOptMessages.incrementAndGet();
				}

				final String msgFileName = String.format("%08d", messagePosition + 1) + ".msg";
				final File messageFile = new File(this.certifiedMessageFolder, msgFileName);
				try {
					AtomicFileOperations.atomicWriteSignedMessage(messageFile, bftMessage);
				} catch (IOException e) {
					e.printStackTrace();
					System.exit(-1);
				}
				this.notifyAll();
			}
		}
	}
}
 
Example 7
Source File: DefaultMessageStore.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public ConsumeQueue findConsumeQueue(String topic, int queueId) {
    ConcurrentMap<Integer, ConsumeQueue> map = consumeQueueTable.get(topic);
    if (null == map) {
        ConcurrentMap<Integer, ConsumeQueue> newMap = new ConcurrentHashMap<Integer, ConsumeQueue>(128);
        ConcurrentMap<Integer, ConsumeQueue> oldMap = consumeQueueTable.putIfAbsent(topic, newMap);
        if (oldMap != null) {
            map = oldMap;
        } else {
            map = newMap;
        }
    }

    ConsumeQueue logic = map.get(queueId);
    if (null == logic) {
        ConsumeQueue newLogic = new ConsumeQueue(
            topic,
            queueId,
            StorePathConfigHelper.getStorePathConsumeQueue(this.messageStoreConfig.getStorePathRootDir()),
            this.getMessageStoreConfig().getMappedFileSizeConsumeQueue(),
            this);
        ConsumeQueue oldLogic = map.putIfAbsent(queueId, newLogic);
        if (oldLogic != null) {
            logic = oldLogic;
        } else {
            logic = newLogic;
        }
    }

    return logic;
}
 
Example 8
Source File: CachedIntrospectionResults.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create CachedIntrospectionResults for the given bean class.
 * @param beanClass the bean class to analyze
 * @return the corresponding CachedIntrospectionResults
 * @throws BeansException in case of introspection failure
 */
@SuppressWarnings("unchecked")
static CachedIntrospectionResults forClass(Class<?> beanClass) throws BeansException {
	CachedIntrospectionResults results = strongClassCache.get(beanClass);
	if (results != null) {
		return results;
	}
	results = softClassCache.get(beanClass);
	if (results != null) {
		return results;
	}

	results = new CachedIntrospectionResults(beanClass);
	ConcurrentMap<Class<?>, CachedIntrospectionResults> classCacheToUse;

	if (ClassUtils.isCacheSafe(beanClass, CachedIntrospectionResults.class.getClassLoader()) ||
			isClassLoaderAccepted(beanClass.getClassLoader())) {
		classCacheToUse = strongClassCache;
	}
	else {
		if (logger.isDebugEnabled()) {
			logger.debug("Not strongly caching class [" + beanClass.getName() + "] because it is not cache-safe");
		}
		classCacheToUse = softClassCache;
	}

	CachedIntrospectionResults existing = classCacheToUse.putIfAbsent(beanClass, results);
	return (existing != null ? existing : results);
}
 
Example 9
Source File: AbstractZookeeperClient.java    From JobX with Apache License 2.0 5 votes vote down vote up
public List<String> addChildListener(String path, final ChildListener listener) {
    ConcurrentMap<ChildListener, TargetChildListener> listeners = childListeners.get(path);
    if (listeners == null) {
        childListeners.putIfAbsent(path, new ConcurrentHashMap<ChildListener, TargetChildListener>());
        listeners = childListeners.get(path);
    }
    TargetChildListener targetListener = listeners.get(listener);
    if (targetListener == null) {
        listeners.putIfAbsent(listener, createTargetChildListener(path, listener));
        targetListener = listeners.get(listener);
    }
    return addTargetChildListener(path, targetListener);
}
 
Example 10
Source File: FastDateParser.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 11
Source File: Utils.java    From spectator with Apache License 2.0 5 votes vote down vote up
/**
 * This method should be used instead of the
 * {@link ConcurrentMap#computeIfAbsent(Object, Function)} call to minimize
 * thread contention. This method does not require locking for the common case
 * where the key exists, but potentially performs additional computation when
 * absent.
 */
public static <K, V> V computeIfAbsent(ConcurrentMap<K, V> map, K k, Function<K, V> f) {
  V v = map.get(k);
  if (v == null) {
    V tmp = f.apply(k);
    v = map.putIfAbsent(k, tmp);
    if (v == null) {
      v = tmp;
    }
  }
  return v;
}
 
Example 12
Source File: AbstractZookeeperClient.java    From FATE-Serving with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> addChildListener(String path, final ChildListener listener) {
    ConcurrentMap<ChildListener, TargetChildListener> listeners = childListeners.get(path);
    if (listeners == null) {
        childListeners.putIfAbsent(path, new ConcurrentHashMap<ChildListener, TargetChildListener>());
        listeners = childListeners.get(path);
    }
    TargetChildListener targetListener = listeners.get(listener);
    if (targetListener == null) {
        listeners.putIfAbsent(listener, createTargetChildListener(path, listener));
        targetListener = listeners.get(listener);
    }
    return addTargetChildListener(path, targetListener);
}
 
Example 13
Source File: ProviderBinder.java    From everrest with 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 14
Source File: QueryContext.java    From kylin with Apache License 2.0 4 votes vote down vote up
public void addRPCStatistics(int ctxId, String rpcServer, String cubeName, String segmentName, long sourceCuboidId,
        long targetCuboidId, long filterMask, Exception e, long rpcCallTimeMs, long skippedRows, long scannedRows,
        long returnedRows, long aggregatedRows, long scannedBytes) {
    RPCStatistics rpcStatistics = new RPCStatistics();
    rpcStatistics.setWrapper(cubeName, rpcServer);
    rpcStatistics.setStats(rpcCallTimeMs, skippedRows, scannedRows, returnedRows, aggregatedRows, scannedBytes);
    rpcStatistics.setException(e);
    rpcStatisticsList.add(rpcStatistics);

    CubeSegmentStatisticsResult cubeSegmentStatisticsResult = cubeSegmentStatisticsResultMap.get(ctxId);
    if (cubeSegmentStatisticsResult == null) {
        logger.warn(CSSR_SHOULD_BE_INIT_FOR_CONTEXT, ctxId);
        return;
    }
    ConcurrentMap<String, ConcurrentMap<String, CubeSegmentStatistics>> cubeSegmentStatisticsMap = cubeSegmentStatisticsResult.cubeSegmentStatisticsMap;
    if (cubeSegmentStatisticsMap == null) {
        logger.warn(CSSM_SHOULD_BE_INIT_FOR_CSSR, cubeSegmentStatisticsResult.queryType);
        return;
    }
    cubeSegmentStatisticsMap.putIfAbsent(cubeName, Maps.<String, CubeSegmentStatistics> newConcurrentMap());
    ConcurrentMap<String, CubeSegmentStatistics> segmentStatisticsMap = cubeSegmentStatisticsMap.get(cubeName);

    CubeSegmentStatistics old = segmentStatisticsMap.putIfAbsent(segmentName, new CubeSegmentStatistics());
    CubeSegmentStatistics segmentStatistics = segmentStatisticsMap.get(segmentName);
    if (old == null) {
        segmentStatistics.setWrapper(cubeName, segmentName, sourceCuboidId, targetCuboidId, filterMask);
    } else if (segmentStatistics.sourceCuboidId != sourceCuboidId
            || segmentStatistics.targetCuboidId != targetCuboidId || segmentStatistics.filterMask != filterMask) {
        StringBuilder inconsistency = new StringBuilder();
        if (segmentStatistics.sourceCuboidId != sourceCuboidId) {
            inconsistency
                    .append("sourceCuboidId exist " + segmentStatistics.sourceCuboidId + INPUT + sourceCuboidId);
        }
        if (segmentStatistics.targetCuboidId != targetCuboidId) {
            inconsistency
                    .append("targetCuboidId exist " + segmentStatistics.targetCuboidId + INPUT + targetCuboidId);
        }
        if (segmentStatistics.filterMask != filterMask) {
            inconsistency.append("filterMask exist " + segmentStatistics.filterMask + INPUT + filterMask);
        }
        logger.error("cube segment statistics wrapper is not consistent due to " + inconsistency.toString());
        return;
    }
    segmentStatistics.addRPCStats(rpcCallTimeMs, skippedRows, scannedRows, returnedRows, aggregatedRows,
            scannedBytes, e == null);
}
 
Example 15
Source File: LocaleProviderAdapter.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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 16
Source File: ThetaVariantEvaluator.java    From gatk with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void update1(VariantContext vc, final ReferenceContext referenceContext, final ReadsContext readsContext, final FeatureContext featureContext) {
    if (vc == null || !vc.isSNP() || (getWalker().ignoreAC0Sites() && vc.isMonomorphicInSamples())) {
        return;
    }

    //this maps allele to a count
    ConcurrentMap<String, Integer> alleleCounts = new ConcurrentHashMap<String, Integer>();

    int numHetsHere = 0;
    int numGenosHere = 0;
    int numIndsHere = 0;

    for (final Genotype genotype : vc.getGenotypes()) {
        numIndsHere++;
        if (!genotype.isNoCall()) {
            //increment stats for heterozygosity
            if (genotype.isHet()) {
                numHetsHere++;
            }

            numGenosHere++;
            //increment stats for pairwise mismatches

            for (Allele allele : genotype.getAlleles()) {
                if (allele.isCalled()) {
                    String alleleString = allele.toString();
                    alleleCounts.putIfAbsent(alleleString, 0);
                    alleleCounts.put(alleleString, alleleCounts.get(alleleString) + 1);
                }
            }
        }
    }
    if (numGenosHere > 0) {
        //only if have one called genotype at least
        this.numSites++;

        this.totalHet += numHetsHere / (double)numGenosHere;

        //compute based on num sites
        float harmonicFactor = 0;
        for (int i = 1; i <= numIndsHere; i++) {
            harmonicFactor += 1.0 / i;
        }
        this.thetaRegionNumSites += 1.0 / harmonicFactor;

        //now compute pairwise mismatches
        float numPairwise = 0;
        int numDiffs = 0;
        for (String allele1 : alleleCounts.keySet()) {
            int allele1Count = alleleCounts.get(allele1);

            for (String allele2 : alleleCounts.keySet()) {
                if (allele1.compareTo(allele2) < 0) {
                    continue;
                }
                if (allele1 .compareTo(allele2) == 0) {
                    numPairwise += allele1Count * (allele1Count - 1) * .5;

                }
                else {
                    int allele2Count = alleleCounts.get(allele2);
                    numPairwise += allele1Count * allele2Count;
                    numDiffs += allele1Count * allele2Count;
                }
            }
        }

        if (numPairwise > 0) {
            this.totalAvgDiffs += numDiffs / numPairwise;
        }
    }
}
 
Example 17
Source File: WeakCache.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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 18
Source File: TenantNetworkWebResource.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a collection of tenantNetworks.
 *
 * @param flag the flag
 * @param networkId network identifier
 * @param node the network json node
 * @return a collection of tenantNetworks
 */
public Iterable<TenantNetwork> changeJson2obj(String flag,
                                              TenantNetworkId networkId,
                                              JsonNode node) {
    checkNotNull(node, JSON_NOT_NULL);
    TenantNetwork network = null;
    ConcurrentMap<TenantNetworkId, TenantNetwork> networksMap = Maps
            .newConcurrentMap();
    checkArgument(node.get("admin_state_up").isBoolean(), "admin_state_up should be boolean");
    checkArgument(node.get("shared").isBoolean(), "shared should be boolean");
    checkArgument(node.get("router:external").isBoolean(), "router:external should be boolean");
    String name = node.get("name").asText();
    boolean adminStateUp = node.get("admin_state_up").asBoolean();
    String state = node.get("status").asText();
    boolean shared = node.get("shared").asBoolean();
    String tenantIdStr = node.get("tenant_id").asText();
    boolean routerExternal = node.get("router:external").asBoolean();
    String type = node.get("provider:network_type").asText();
    String physicalNetwork = node.get("provider:physical_network").asText();
    String segmentationIdStr = node.get("provider:segmentation_id").asText();
    SegmentationId segmentationId = SegmentationId.segmentationId(segmentationIdStr);
    TenantId tenantId = TenantId.tenantId(tenantIdStr);
    if (segmentationIdStr == null || "null".equals(segmentationIdStr)) {
        segmentationId = get(VtnRscService.class).getL3vni(tenantId);
    }
    TenantNetworkId id = null;
    if (flag.equals(CREATE_NETWORK)) {
        id = TenantNetworkId.networkId(node.get("id").asText());
    } else if (flag.equals(UPDATE_NETWORK)) {
        id = networkId;
    }
    network = new DefaultTenantNetwork(
                                       id,
                                       name,
                                       adminStateUp,
                                       isState(state),
                                       shared,
                                       tenantId,
                                       routerExternal,
                                       isType(type),
                                       PhysicalNetwork
                                               .physicalNetwork(physicalNetwork),
                                       segmentationId);
    networksMap.putIfAbsent(id, network);

    return Collections.unmodifiableCollection(networksMap.values());
}
 
Example 19
Source File: LocaleProviderAdapter.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * 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, forType(Type.FALLBACK));
    return forType(Type.FALLBACK);
}
 
Example 20
Source File: GridConcurrentHashSet.java    From ignite with Apache License 2.0 2 votes vote down vote up
/**
 * Note that unlike regular add operation on a set, this method will only
 * add the passed in element if it's not already present in set.
 *
 * @param e Element to add.
 * @return Value previously present in set or {@code null} if set didn't have this value.
 */
@Nullable public E addx(E e) {
    ConcurrentMap<E, E> m = (ConcurrentMap<E, E>)map;

    return m.putIfAbsent(e, e);
}