下面列出了java.util.AbstractSet#java.util.concurrent.ConcurrentHashMap 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Load a class by name.
*
* @param name the class name.
* @return the class object.
* @throws ClassNotFoundException if the class is not found.
*/
public Class<?> getClassByName(String name) throws ClassNotFoundException {
Map<String, Class<?>> map = CACHE_CLASSES.get(classLoader);
if (map == null) {
Map<String, Class<?>> newMap = new ConcurrentHashMap<>();
map = CACHE_CLASSES.putIfAbsent(classLoader, newMap);
if (map == null) {
map = newMap;
}
}
Class clazz = map.get(name);
if (clazz == null) {
clazz = Class.forName(name, true, classLoader);
if (clazz != null) {
map.put(name, clazz);
}
}
return clazz;
}
private static Map<CellLoc, Short> calculateCellLocs(WorldServer world) {
ConcurrentHashMap<CellLoc, Short> oldDat = MazeHandler.labyrinth;
ConcurrentHashMap<CellLoc, Short> bufferOld = new ConcurrentHashMap<CellLoc, Short>(labyrinthCopy);
MazeHandler.labyrinth = labyrinthCopy;
int chX = getHighestPossibleRandWH(); //To ensure we're always +x and +z
int chZ = getHighestPossibleRandWH();
int w = randWH(world.rand);
int h = randWH(world.rand);
while (MazeHandler.mazesInRange(chX, chZ, w, h)) {
chX++; //We grow the mazes in +x direction!
}
MazeThread mt = new MazeThread(chX, chZ, w, h, world.rand.nextLong());
mt.run();
Map<CellLoc, Short> locs = calculateDifferences(bufferOld);
labyrinthCopy = MazeHandler.labyrinth;
MazeHandler.labyrinth = oldDat;
return locs;
}
private static <T> Collection<Object[]> makeMapsMoreTypes(String desc,
T[] keys,
T val) {
Collection<Object[]> cases = new ArrayList<>();
cases.add(createCase("Hashtable with " + desc,
new Hashtable<>(), keys, val));
cases.add(createCase("IdentityHashMap with " + desc,
new IdentityHashMap<>(), keys, val));
cases.add(createCase("TreeMap with " + desc,
new TreeMap<>(), keys, val));
cases.add(createCase("WeakHashMap with " + desc,
new WeakHashMap<>(), keys, val));
cases.add(createCase("ConcurrentHashMap with " + desc,
new ConcurrentHashMap<>(), keys, val));
cases.add(createCase("ConcurrentSkipListMap with " + desc,
new ConcurrentSkipListMap<>(), keys, val));
return cases;
}
public static void main(String[] args) throws Exception {
final ConcurrentHashMap<String, String> concurrentHashMap =
new ConcurrentHashMap<>();
concurrentHashMap.put("One", "Un");
concurrentHashMap.put("Two", "Deux");
concurrentHashMap.put("Three", "Trois");
Set<Map.Entry<String, String>> entrySet = concurrentHashMap.entrySet();
HashSet<Map.Entry<String, String>> hashSet = new HashSet<>(entrySet);
if (false == hashSet.equals(entrySet)) {
throw new RuntimeException("Test FAILED: Sets are not equal.");
}
if (hashSet.hashCode() != entrySet.hashCode()) {
throw new RuntimeException("Test FAILED: Set's hashcodes are not equal.");
}
}
/**
* Associates given value {@code v} with this ClassLoaderValue and given
* ClassLoader and returns {@code null} if there was no previously associated
* value or does nothing and returns previously associated value if there
* was one.
*
* @param cl the ClassLoader for the associated value
* @param v the value to associate
* @return previously associated value or null if there was none
*/
public V putIfAbsent(ClassLoader cl, V v) {
ConcurrentHashMap<CLV, Object> map = map(cl);
@SuppressWarnings("unchecked")
CLV clv = (CLV) this;
while (true) {
try {
Object val = map.putIfAbsent(clv, v);
return extractValue(val);
} catch (Memoizer.RecursiveInvocationException e) {
// propagate RecursiveInvocationException for the same key that
// is just being calculated in computeIfAbsent
throw e;
} catch (Throwable t) {
// don't propagate exceptions thrown from foreign Memoizer -
// pretend that there was no entry and retry
// (foreign computeIfAbsent invocation will try to remove it anyway)
}
// TODO:
// Thread.onSpinLoop(); // when available
}
}
/**
* Constructor that implements the {@link CacheTransactionManager} interface.
* Only only one instance per {@link com.gemstone.gemfire.cache.Cache}
*/
public TXManagerImpl(CachePerfStats cachePerfStats, LogWriterI18n logWriter,
GemFireCacheImpl cache) {
this.cache = cache;
this.dm = cache.getDistributedSystem().getDistributionManager();
this.cachePerfStats = cachePerfStats;
this.logWriter = logWriter;
this.hostedTXStates = new CustomEntryConcurrentHashMap<TXId, TXStateProxy>(
128, CustomEntryConcurrentHashMap.DEFAULT_LOAD_FACTOR,
TXMAP_CONCURRENCY);
this.suspendedTXs = new ConcurrentHashMap<TXId, TXStateInterface>();
this.finishedTXStates = new TXFinishedMap(cache.getDistributedSystem(),
cache.getCancelCriterion());
this.waitMap = new ConcurrentHashMap<TransactionId, Queue<Thread>>();
this.expiryTasks = new ConcurrentHashMap<TransactionId, SystemTimerTask>();
}
private void setAuthenticator(OkHttpClient.Builder okHttpClientBuilder, ConfigurationContext context) {
final String authUser = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_USERNAME).evaluateAttributeExpressions().getValue());
this.basicUser = authUser;
isDigest = context.getProperty(PROP_DIGEST_AUTH).asBoolean();
final String authPass = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_PASSWORD).evaluateAttributeExpressions().getValue());
this.basicPass = authPass;
// If the username/password properties are set then check if digest auth is being used
if (!authUser.isEmpty() && isDigest) {
/*
* OkHttp doesn't have built-in Digest Auth Support. A ticket for adding it is here[1] but they authors decided instead to rely on a 3rd party lib.
*
* [1] https://github.com/square/okhttp/issues/205#issuecomment-154047052
*/
final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
com.burgstaller.okhttp.digest.Credentials credentials = new com.burgstaller.okhttp.digest.Credentials(authUser, authPass);
final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(credentials);
okHttpClientBuilder.interceptors().add(new AuthenticationCacheInterceptor(authCache));
okHttpClientBuilder.authenticator(new CachingAuthenticatorDecorator(digestAuthenticator, authCache));
}
}
/**
* spits input string, converts keys and values to lower case, and replaces '"'
* and ''' if any
*
* @param style the input style string
* @return the sanitised map
*/
public static Map<String, String> splitIntoMap(final String style) {
final ConcurrentHashMap<String, String> retVal = new ConcurrentHashMap<>();
if (style == null) {
return retVal;
}
final String[] keyVals = AT_LEAST_ONE_WHITESPACE_PATTERN.matcher(style.toLowerCase(Locale.UK)).replaceAll("").split(";");
for (final String keyVal : keyVals) {
final String[] parts = STYLE_ASSIGNMENT_PATTERN.split(keyVal, 2);
if (parts.length <= 1) {
continue;
}
retVal.put(parts[0], QUOTES_PATTERN.matcher(parts[1]).replaceAll(""));
}
return retVal;
}
/**
* Determines and reports any discrepancies between the current thread's Code Systems cache and the contents of the database CODE_SYSTEMS table.
* @param dao A Parameter DAO instance
* @return String - A report detailing cache/db discrepancies.
*/
public static String reportCacheDiscrepancies(ParameterDAO dao) {
String tenantDatstoreCacheName = getCacheNameForTenantDatastore();
Map<String, Integer> dbMap;
ConcurrentHashMap<String,Integer> cachedMap = codeSystemIdMaps.get(tenantDatstoreCacheName);
String discrepancies = "";
if (enabled) {
try {
dbMap = dao.readAllCodeSystems();
discrepancies = CacheUtil.reportCacheDiscrepancies("CodeSystemsCache", cachedMap, dbMap);
}
catch (FHIRPersistenceDBConnectException | FHIRPersistenceDataAccessException e) {
log.log(Level.SEVERE, "Failure obtaining all code systems." , e);
discrepancies = CacheUtil.NEWLINE + "Could not report on CodeSystems cache discrepancies." + CacheUtil.NEWLINE;
}
}
return discrepancies;
}
public synchronized void initApp() {
synchronized (lockObj) {
Transaction transaction = Tracer.newTransaction("AppCache", "initApp");
try {
isReinit = true;
List<AppEntity> appEntities = appRepository.findAll();
Map<String, AppDto> servMap = doUpdateCache(appEntities);
Map<String, AppDto> servMap1 = new ConcurrentHashMap<>(servMap);
appRefMap.set(servMap1);
log.info("App 初始化完成!");
initServCounter.inc();
isReinit = false;
transaction.setStatus(Transaction.SUCCESS);
} catch (Exception e) {
transaction.setStatus(e);
} finally {
transaction.complete();
}
}
}
@Override
public void rollback() {
preparedState = null;
if (commitedState != null) {
state = commitedState.state;
} else {
state = new ConcurrentHashMap<>();
}
}
/**
* Get best price/qty on the order book for all symbols.
*
* @return map of BinanceTicker
* @throws BinanceApiException in case of any error
*/
public Map<String, BinanceTicker> allBookTickersMap() throws BinanceApiException {
String lastResponse = (new BinanceRequest(baseUrl + "v1/ticker/allBookTickers")).read().getLastResponse();
Type listType = new TypeToken<List<BinanceTicker>>() {
}.getType();
Map<String, BinanceTicker> mapTickers = new ConcurrentHashMap<>();
List<BinanceTicker> ticker = new Gson().fromJson(lastResponse, listType);
for (BinanceTicker t : ticker) mapTickers.put(t.getSymbol(), t);
return mapTickers;
}
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);
}
}
}
@Test (expected = ApplicationNotFoundException.class)
public void testMoveAbsentApplication() throws YarnException {
RMContext rmContext = mock(RMContext.class);
when(rmContext.getRMApps()).thenReturn(
new ConcurrentHashMap<ApplicationId, RMApp>());
ClientRMService rmService = new ClientRMService(rmContext, null, null,
null, null, null);
ApplicationId applicationId =
BuilderUtils.newApplicationId(System.currentTimeMillis(), 0);
MoveApplicationAcrossQueuesRequest request =
MoveApplicationAcrossQueuesRequest.newInstance(applicationId, "newqueue");
rmService.moveApplicationAcrossQueues(request);
}
AbstractSourceSubscriber(Executor executor, int initialCapacityForGroups,
Subscriber<? super GroupedPublisher<Key, T>> target) {
this.executor = executor;
this.target = target;
// loadFactor: 1 to have table size as expected groups.
groups = new ConcurrentHashMap<>(initialCapacityForGroups, 1, 1);
}
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);
}
}
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);
}
/**
* reduceEntriesSequentially accumulates across all entries
*/
public void testReduceEntriesSequentially() {
ConcurrentHashMap<Long, Long> m = longMap();
Map.Entry<Long,Long> r;
r = m.reduceEntries(Long.MAX_VALUE, new AddKeys());
assertEquals(r.getKey().longValue(), (long)SIZE * (SIZE - 1) / 2);
}
public Object compute() {
ConcurrentHashMap<ChronoVertex, Long> gamma = new ConcurrentHashMap<ChronoVertex, Long>();
ChronoGraph g = new ChronoGraph();
gamma.put(source.getVertex(), source.getTimestamp());
PipeFunction<VertexEvent, Boolean> exceedBound2 = new PipeFunction<VertexEvent, Boolean>() {
@Override
public Boolean compute(VertexEvent ve) {
if (gamma.containsKey(ve.getVertex()) && (ve.getTimestamp() >= gamma.get(ve.getVertex()))) {
return false;
}
return true;
}
};
PipeFunction<List<VertexEvent>, Object> storeGamma = new PipeFunction<List<VertexEvent>, Object>() {
@Override
public Object compute(List<VertexEvent> vertexEvents) {
vertexEvents.parallelStream().forEach(ve -> {
gamma.put(ve.getVertex(), ve.getTimestamp());
});
return null;
}
};
LoopPipeFunction exitIfEmptyIterator = new LoopPipeFunction() {
@Override
public boolean compute(Object argument, Map<Object, Object> currentPath, int loopCount) {
List list = (List) argument;
if (list == null || list.size() == 0)
return false;
return true;
}
};
return new TraversalEngine(g, source, false, true, VertexEvent.class).as("s").scatter().oute(label, AC.$gt)
.filter(exceedBound2).gather().elementDedup(FC.$min).sideEffect(storeGamma)
.loop("s", exitIfEmptyIterator).path();
}
/**
* compatible with jdk6
*/
private <T extends Metric> T computeIfAbsent(ConcurrentHashMap<Id, Metric> map, Id id,
NewMetricFunction<? extends Metric> f) {
Metric m = map.get(id);
if (m == null) {
//如果metrics过多了,则给个noop,并给出提示;
if (map.size() >= config.getInt(LOOKOUT_MAX_METRICS_NUMBER,
MetricConfig.DEFAULT_MAX_METRICS_NUM)) {
if (maxNumWarning) {
logger
.warn(
"metrics number reach max limit: {}! Do not record this new metric(id:{}).",
config.getInt(LOOKOUT_MAX_METRICS_NUMBER,
MetricConfig.DEFAULT_MAX_METRICS_NUM), id);
maxNumWarning = false;
}
return (T) f.noopMetric();
}
//if the key exists,this execution is useless!
Metric tmp = f.apply(id);
m = map.putIfAbsent(id, tmp);
if (m == null) {
//first register
m = tmp;
onMetricAdded(tmp);
}
}
return (T) m;
}
/**
* enumeration returns an enumeration containing the correct
* elements
*/
public void testEnumeration() {
ConcurrentHashMap map = map5();
Enumeration e = map.elements();
int count = 0;
while (e.hasMoreElements()) {
count++;
e.nextElement();
}
assertEquals(5, count);
}
public static Map<String, TablistVariable> getFunnyVariables() {
if (FUNNY_VARIABLES.isEmpty()) {
createFunnyVariables();
}
return new ConcurrentHashMap<>(FUNNY_VARIABLES);
}
@Autowired
public EventSourceSyncDurationLogger(final Optional<List<EventSource>> eventSources) {
allChannels = eventSources.orElse(Collections.emptyList())
.stream()
.map(EventSource::getChannelName)
.collect(toSet());
healthyChannels = ConcurrentHashMap.newKeySet();
}
@Override
public void addCounts(UUID jobId, Map<String, Integer> newCounts) {
if (newCounts == null) {
return;
}
newCounts.forEach(
(dataName, dataCount) ->
counts
.computeIfAbsent(jobId, k -> new ConcurrentHashMap<>())
.merge(dataName, dataCount, Integer::sum));
}
public NMTokenSecretManagerInRM(Configuration conf) {
this.conf = conf;
timer = new Timer();
rollingInterval = this.conf.getLong(
YarnConfiguration.RM_NMTOKEN_MASTER_KEY_ROLLING_INTERVAL_SECS,
YarnConfiguration.DEFAULT_RM_NMTOKEN_MASTER_KEY_ROLLING_INTERVAL_SECS)
* 1000;
// Add an activation delay. This is to address the following race: RM may
// roll over master-key, scheduling may happen at some point of time, an
// NMToken created with a password generated off new master key, but NM
// might not have come again to RM to update the shared secret: so AM has a
// valid password generated off new secret but NM doesn't know about the
// secret yet.
// Adding delay = 1.5 * expiry interval makes sure that all active NMs get
// the updated shared-key.
this.activationDelay =
(long) (conf.getLong(YarnConfiguration.RM_NM_EXPIRY_INTERVAL_MS,
YarnConfiguration.DEFAULT_RM_NM_EXPIRY_INTERVAL_MS) * 1.5);
LOG.info("NMTokenKeyRollingInterval: " + this.rollingInterval
+ "ms and NMTokenKeyActivationDelay: " + this.activationDelay
+ "ms");
if (rollingInterval <= activationDelay * 2) {
throw new IllegalArgumentException(
YarnConfiguration.RM_NMTOKEN_MASTER_KEY_ROLLING_INTERVAL_SECS
+ " should be more than 3 X "
+ YarnConfiguration.RM_NM_EXPIRY_INTERVAL_MS);
}
appAttemptToNodeKeyMap =
new ConcurrentHashMap<ApplicationAttemptId, HashSet<NodeId>>();
}
public SchemaVersionInfoCache(final SchemaVersionRetriever schemaRetriever,
final int schemaCacheSize,
final long schemaCacheExpiryInMilliSecs) {
idWithNameVersion = new ConcurrentHashMap<>(schemaCacheSize);
nameVersionWithIds = new ConcurrentHashMap<>(schemaCacheSize);
loadingCache = createLoadingCache(schemaRetriever, schemaCacheSize, schemaCacheExpiryInMilliSecs);
}
public void run() throws Exception {
TChannel tchannel = new TChannel.Builder("ping-client").build();
SubChannel subChannel = tchannel.makeSubChannel("ping-server");
final ConcurrentHashMap<String, AtomicInteger> msgs = new ConcurrentHashMap<>();
final CountDownLatch done = new CountDownLatch(requests);
for (int i = 0; i < requests; i++) {
JsonRequest<Ping> request = new JsonRequest.Builder<Ping>("ping-server", "ping")
.setBody(new Ping("{'key': 'ping?'}"))
.setHeader("some", "header")
.setTimeout(100 + i)
.build();
TFuture<JsonResponse<Pong>> f = subChannel.send(
request,
InetAddress.getByName(host),
port
);
f.addCallback(new TFutureCallback<JsonResponse<Pong>>() {
@Override
public void onResponse(JsonResponse<Pong> pongResponse) {
done.countDown();
String msg = pongResponse.toString();
AtomicInteger count = msgs.putIfAbsent(msg, new AtomicInteger(1));
if (count != null) {
count.incrementAndGet();
}
}
});
}
done.await();
for (Map.Entry<String, AtomicInteger> stringIntegerEntry : msgs.entrySet()) {
System.out.println(String.format("%s%n\tcount:%s",
stringIntegerEntry.getKey(), stringIntegerEntry.getValue()
));
}
tchannel.shutdown(false);
}
@Override
public void run() {
while( !_start ) {
try { Thread.sleep(1); } catch( Exception e ){}
}
long nano1 = System.nanoTime();
int total = 0;
if( _read_ratio == 0 ) {
total = run_churn();
} else {
if( _hash instanceof ConcurrentLinkedHashMap) {
total = run_normal( (ConcurrentLinkedHashMap<String,String>) _hash);
} else if( _hash instanceof NonBlockingHashMap ) {
total = run_normal( (NonBlockingHashMap<String,String>) _hash);
} else if( _hash instanceof ConcurrentHashMap ) {
total = run_normal( (ConcurrentHashMap<String,String>) _hash);
} else {
total = run_normal(_hash);
}
}
_ops[_tnum] = total;
long nano2 = System.nanoTime();
_nanos[_tnum] = (nano2-nano1);
}
@Override
public Integer findId(String stringType, String value) {
ConcurrentHashMap<String, Integer> typeValue2Key = vale2KeyMapping.computeIfAbsent(stringType, key->new ConcurrentHashMap<>());
int resultKey = typeValue2Key.computeIfAbsent(value, k->getOrInsertId(stringType,value));
return resultKey;
}
public WorldGen(World w)
{
world = w;
islandCache = Collections.synchronizedMap(new ConcurrentHashMap<Integer, CachedIsland>());
mapQueue = new PriorityBlockingQueue<Integer>();
buildThreads = new ThreadBuild[TFCOptions.maxThreadsForIslandGen];
EMPTY_MAP = new IslandMap(ISLAND_SIZE, 0);
IslandParameters ip = createParams(0, -2, 0);
ip.setIslandTemp(ClimateTemp.TEMPERATE);
ip.setIslandMoisture(Moisture.HIGH);
EMPTY_MAP.newIsland(ip);
EMPTY_MAP.generateFake();
}