下面列出了java.util.concurrent.ConcurrentHashMap#remove ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void cmnClearRegion(long drId, ConcurrentHashMap<DiskStoreID, RegionVersionHolder<DiskStoreID>> memberToVersion) {
DiskRegionView drv = getDiskRegionById(drId);
// getLogger().info(LocalizedStrings.DEBUG, "DEBUG: DiskInitFile IFREC_CLEAR_REGION_ID drId=" + drId + " clearOplogEntryId=" + clearOplogEntryId);
if (drv.getClearRVV() == null) {
this.ifLiveRecordCount++;
}
// otherwise previous clear is cancelled so don't change liveRecordCount
this.ifTotalRecordCount++;
DiskStoreID ownerId = parent.getDiskStoreID();
//Create a fake RVV for clear purposes. We only need to memberToVersion information
RegionVersionHolder<DiskStoreID> ownerExceptions = memberToVersion.remove(ownerId);
long ownerVersion = ownerExceptions == null ? 0 : ownerExceptions.getVersion();
RegionVersionVector rvv = new DiskRegionVersionVector(ownerId,
memberToVersion, ownerVersion, new ConcurrentHashMap(), 0L, false,
ownerExceptions);
drv.setClearRVV(rvv);
}
public void removeChannelContext(String inboundName, String subscriberPath, InboundWebsocketChannelContext ctx) {
ConcurrentHashMap<String, List<InboundWebsocketChannelContext>> subscriberPathMap = inboundSubscriberPathMap
.get(inboundName);
List<InboundWebsocketChannelContext> listContext = subscriberPathMap.get(subscriberPath);
for (Object context : listContext.toArray()) {
if (((InboundWebsocketChannelContext) context).getChannelIdentifier().equals(ctx.getChannelIdentifier())) {
listContext.remove(context);
break;
}
}
if (listContext.isEmpty()) {
listContext.clear();
subscriberPathMap.remove(subscriberPath);
}
if (subscriberPathMap.isEmpty()) {
subscriberPathMap.clear();
inboundSubscriberPathMap.remove(inboundName);
}
}
public void benchConcurrentHashMap() throws Exception {
ConcurrentHashMap<Long, String> map = new ConcurrentHashMap<>(N, 0.66f, 1);
for (long i = 0; i < Iterations; i++) {
for (int j = 0; j < N; j++) {
map.put(i, "value");
}
for (long h = 0; h < ReadIterations; h++) {
for (int j = 0; j < N; j++) {
map.get(i);
}
}
for (int j = 0; j < N; j++) {
map.remove(i);
}
}
}
public void benchConcurrentHashMap() throws Exception {
ConcurrentHashMap<Long, String> map = new ConcurrentHashMap<Long, String>(N, 0.66f, 1);
for (long i = 0; i < Iterations; i++) {
for (int j = 0; j < N; j++) {
map.put(i, "value");
}
for (long h = 0; h < ReadIterations; h++) {
for (int j = 0; j < N; j++) {
map.get(i);
}
}
for (int j = 0; j < N; j++) {
map.remove(i);
}
}
}
/**
* Remove appear event
*/
public void unbindAppearEvent(WXComponent component) {
ConcurrentHashMap<String, AppearData> appearMap = mAppearMap
.get(getInnerView());
if (appearMap == null) {
return;
}
AppearData appearData = appearMap.get(component.getRef());
if (appearData == null) {
return;
}
appearData.hasAppear = false;
if (!appearData.hasDisappear) {
appearMap.remove(component.getRef());
}
}
/**
* 在内存中汇总统计信息。
*/
public void write(Object[] keys, Object[] fields, long... values) {
if (values.length != 2) {
// XXX: 这里限制 BufferedLogWriter 只接受 count + value 的输入
throw new IllegalArgumentException("Only support 2 values!");
}
ConcurrentHashMap<LogKey, Reference<LogCounter>> map = this.map;
LogKey logKey = new LogKey(keys);
LogCounter counter;
for (;;) {
Reference<LogCounter> entry = map.get(logKey);
if (entry == null) {
LogCounter newCounter = new LogCounter(logKey, (fields == null) ? keys : fields);
newCounter.stat(values[0], values[1]);
entry = map.putIfAbsent(logKey, createLogRef(logKey, newCounter));
if (entry == null) {
expungeLogRef();
return;
}
}
counter = entry.get();
if (counter != null) {
counter.stat(values[0], values[1]);
return;
}
map.remove(logKey);
}
}
public WeakKey(K key, Cleaner c, ConcurrentHashMap<WeakKey<K>, ?> map) {
super(key);
this.hash = key.hashCode();
this.map = map;
cleanable = new WeakCleanable<Object>(key, c) {
protected void performCleanup() {
map.remove(WeakKey.this);
}
};
}
private void releaseCountDownLatch(ConcurrentHashMap<String,
CountDownLatch> latchMap,
String latchKey) {
CountDownLatch completedLatch = latchMap.remove(latchKey);
if (completedLatch != null) {
completedLatch.countDown();
}
}
protected TableDescriptor selectTable(ConcurrentHashMap<TableName, TableDescriptor> tableMap)
{
// synchronization to prevent removal from multiple threads
synchronized (tableMap){
// randomly select table from tableMap
if (tableMap.isEmpty()) {
return null;
}
ArrayList<TableName> tableList = new ArrayList<>(tableMap.keySet());
TableName randomKey = tableList.get(RandomUtils.nextInt(0, tableList.size()));
TableDescriptor randomTd = tableMap.remove(randomKey);
return randomTd;
}
}
/**
* remove(key,value) removes only if pair present
*/
public void testRemove2() {
ConcurrentHashMap map = map5();
map.remove(five, "E");
assertEquals(4, map.size());
assertFalse(map.containsKey(five));
map.remove(four, "A");
assertEquals(4, map.size());
assertTrue(map.containsKey(four));
}
@Get("json")
public Representation getStatus(final Representation request) {
final RestOperationStatusMessage status = new RestOperationStatusMessage();
ConcurrentHashMap<String, Future<?>> opStatuses = null;
final String id = getQueryValue("id");
try {
// look up the operation status
opStatuses =
(ConcurrentHashMap<String, Future<?>>) getApplication().getContext().getAttributes().get(
"asyncOperationStatuses");
if (opStatuses.get(id) != null) {
final Future<?> future = opStatuses.get(id);
if (future.isDone()) {
status.status = RestOperationStatusMessage.StatusType.COMPLETE;
status.message = "operation success";
status.data = future.get();
opStatuses.remove(id);
} else {
status.status = RestOperationStatusMessage.StatusType.RUNNING;
}
return new JacksonRepresentation<>(status);
}
} catch (final Exception e) {
LOGGER.error("Error exception: ", e);
status.status = RestOperationStatusMessage.StatusType.ERROR;
status.message = "exception occurred";
status.data = e;
if (opStatuses != null) {
opStatuses.remove(id);
}
return new JacksonRepresentation<>(status);
}
status.status = RestOperationStatusMessage.StatusType.ERROR;
status.message = "no operation found for ID: " + id;
return new JacksonRepresentation<>(status);
}
/**
* Removes weak keys from the map that have been enqueued
* on the reference queue and are no longer in use.
*/
private static void processQueue(ReferenceQueue<Key> queue,
ConcurrentHashMap<? extends
WeakReference<Key>, ?> pdMap) {
Reference<? extends Key> ref;
while ((ref = queue.poll()) != null) {
pdMap.remove(ref);
}
}
protected void deleteAllMarkedPoints() {
for (final EditableDataSet dataSet : markedPoints.keySet()) {
final ConcurrentHashMap<Integer, SelectedDataPoint> dataPoints = markedPoints.get(dataSet);
for (final Integer dataPointIndex : dataPoints.keySet()) {
final SelectedDataPoint dataPoint = dataPoints.get(dataPointIndex);
if (dataPoint.delete()) {
dataPoints.remove(dataPointIndex);
}
}
}
updateMarker();
}
/**
* remove(key,value) removes only if pair present
*/
public void testRemove2() {
ConcurrentHashMap map = map5();
map.remove(five, "E");
assertEquals(4, map.size());
assertFalse(map.containsKey(five));
map.remove(four, "A");
assertEquals(4, map.size());
assertTrue(map.containsKey(four));
}
public void unlockBatch(final String group, final Set<MessageQueue> mqs, final String clientId) {
try {
this.lock.lockInterruptibly();
try {
ConcurrentHashMap<MessageQueue, LockEntry> groupValue = this.mqLockTable.get(group);
if (null != groupValue) {
for (MessageQueue mq : mqs) {
LockEntry lockEntry = groupValue.get(mq);
if (null != lockEntry) {
if (lockEntry.getClientId().equals(clientId)) {
groupValue.remove(mq);
log.info("unlockBatch, Group: {} {} {}",
group,
mq,
clientId);
} else {
log.warn("unlockBatch, but mq locked by other client: {}, Group: {} {} {}",
lockEntry.getClientId(),
group,
mq,
clientId);
}
} else {
log.warn("unlockBatch, but mq not locked, Group: {} {} {}",
group,
mq,
clientId);
}
}
} else {
log.warn("unlockBatch, group not exist, Group: {} {}",
group,
clientId);
}
} finally {
this.lock.unlock();
}
} catch (InterruptedException e) {
log.error("putMessage exception", e);
}
}
public void remove(K1 key1, K2 key2) {
ConcurrentHashMap<K2, V> k2_v = k1_k2V_map.get(key1);
if (k2_v != null) {
k2_v.remove(key2);
}
}
static <K, V> V synchronizedLoad(CacheConfig config, AbstractCache<K,V> abstractCache,
K key, Function<K, V> newLoader, Consumer<V> cacheUpdater) {
ConcurrentHashMap<Object, LoaderLock> loaderMap = abstractCache.initOrGetLoaderMap();
Object lockKey = buildLoaderLockKey(abstractCache, key);
while (true) {
boolean create[] = new boolean[1];
LoaderLock ll = loaderMap.computeIfAbsent(lockKey, (unusedKey) -> {
create[0] = true;
LoaderLock loaderLock = new LoaderLock();
loaderLock.signal = new CountDownLatch(1);
loaderLock.loaderThread = Thread.currentThread();
return loaderLock;
});
if (create[0] || ll.loaderThread == Thread.currentThread()) {
try {
V loadedValue = newLoader.apply(key);
ll.success = true;
ll.value = loadedValue;
cacheUpdater.accept(loadedValue);
return loadedValue;
} finally {
if (create[0]) {
ll.signal.countDown();
loaderMap.remove(lockKey);
}
}
} else {
try {
Duration timeout = config.getPenetrationProtectTimeout();
if (timeout == null) {
ll.signal.await();
} else {
boolean ok = ll.signal.await(timeout.toMillis(), TimeUnit.MILLISECONDS);
if(!ok) {
logger.info("loader wait timeout:" + timeout);
return newLoader.apply(key);
}
}
} catch (InterruptedException e) {
logger.warn("loader wait interrupted");
return newLoader.apply(key);
}
if (ll.success) {
return (V) ll.value;
} else {
continue;
}
}
}
}
/**
* Scan all metrics for the given host, purging any whose declared DMax has
* been exceeded.
*
* @param hostName
* The host name.
*/
private void purgeOldMetrics(final String hostName) {
// Lookup counters for that host.
final ConcurrentHashMap<String/* mungedMetricName */, TimestampMetricValue> hostCounters = knownHosts
.get(hostName);
if (hostCounters == null) {
// Nothing there.
return;
}
final Iterator<TimestampMetricValue> itr = hostCounters.values()
.iterator();
while (itr.hasNext()) {
final TimestampMetricValue tmv = itr.next();
final int dmax = tmv.getMetadata().getDMax();
if (dmax == 0) {
// Zero means keep forever.
continue;
}
final int age = tmv.getAge();
if (age > dmax) {
/*
* This metric has not been updated recently. Drop it.
*/
hostCounters.remove(tmv.getMetadata().getMetricName(), tmv);
if (log.isInfoEnabled())
log.info("Purged metric="
+ tmv.getMetadata().getMetricName() + " for host="
+ hostName + ", last update was " + age
+ " seconds ago");
}
}
}
public void stopJob(Batcher batcher, ConcurrentHashMap<String, JobTicket> activeJobs) {
if (batcher instanceof BatcherImpl) {
((BatcherImpl) batcher).stop();
}
if (batcher.getJobId() != null) activeJobs.remove(batcher.getJobId());
}
protected void findDataPoint(final Axis xAxis, final Axis yAxis, final List<DataSet> dataSets) {
if (xAxis == null || yAxis == null || dataSets == null) {
return;
}
final double xMinScreen = Math.min(selectStartPoint.getX(), selectEndPoint.getX());
final double xMaxScreen = Math.max(selectStartPoint.getX(), selectEndPoint.getX());
final double yMinScreen = Math.min(selectStartPoint.getY(), selectEndPoint.getY());
final double yMaxScreen = Math.max(selectStartPoint.getY(), selectEndPoint.getY());
for (final DataSet ds : dataSets) {
if (!(ds instanceof EditableDataSet)) {
continue;
}
final EditableDataSet dataSet = (EditableDataSet) ds;
final int indexMin = Math.max(0, ds.getIndex(DataSet.DIM_X, xAxis.getValueForDisplay(xMinScreen)));
final int indexMax = Math.min(ds.getIndex(DataSet.DIM_X, xAxis.getValueForDisplay(xMaxScreen)) + 1,
ds.getDataCount());
// N.B. (0,0) screen coordinate is in the top left corner vs. normal
// 0,0 in the bottom left -> need to invert limits
final double yMax = yAxis.getValueForDisplay(yMinScreen);
final double yMin = yAxis.getValueForDisplay(yMaxScreen);
final ConcurrentHashMap<Integer, SelectedDataPoint> dataSetHashMap = markedPoints.computeIfAbsent(dataSet,
k -> new ConcurrentHashMap<>());
for (int i = indexMin; i < indexMax; i++) {
final double y = dataSet.get(DataSet.DIM_Y, i);
if ((y >= yMin) && (y <= yMax)) {
if (isShiftDown()) {
// add if not existing/remove if existing
if (dataSetHashMap.get(i) != null) {
dataSetHashMap.remove(i);
} else {
dataSetHashMap.put(i, new SelectedDataPoint(xAxis, yAxis, dataSet, i));
}
} else {
dataSetHashMap.put(i, new SelectedDataPoint(xAxis, yAxis, dataSet, i));
}
}
}
}
}