Java Code Examples for java.util.concurrent.ConcurrentHashMap#remove()

The following examples show how to use java.util.concurrent.ConcurrentHashMap#remove() . 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: DiskInitFile.java    From gemfirexd-oss with Apache License 2.0 8 votes vote down vote up
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);
  }
 
Example 2
Source File: WebsocketSubscriberPathManager.java    From micro-integrator with Apache License 2.0 7 votes vote down vote up
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);
    }
}
 
Example 3
Source File: WXScroller.java    From weex with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
  }
}
 
Example 4
Source File: ConcurrentLongHashMapTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
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);
      }
   }
}
 
Example 5
Source File: ConcurrentOpenHashMapTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example 6
Source File: ConcurrentHashMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example 7
Source File: EditDataSet.java    From chart-fx with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 8
Source File: ProtectionDomain.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 9
Source File: AsyncOperationStatusResource.java    From geowave with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 10
Source File: ConcurrentHashMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example 11
Source File: IntegrationTestDDLMasterFailover.java    From hbase with Apache License 2.0 5 votes vote down vote up
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;
  }
}
 
Example 12
Source File: GitService.java    From gitpitch with MIT License 5 votes vote down vote up
private void releaseCountDownLatch(ConcurrentHashMap<String,
        CountDownLatch> latchMap,
                                   String latchKey) {

    CountDownLatch completedLatch = latchMap.remove(latchKey);

    if (completedLatch != null) {
        completedLatch.countDown();
    }

}
 
Example 13
Source File: CleanerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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);
        }
    };
}
 
Example 14
Source File: SoftRefLogWriter.java    From tddl with Apache License 2.0 5 votes vote down vote up
/**
 * 在内存中汇总统计信息。
 */
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);
    }
}
 
Example 15
Source File: GangliaState.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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");

		}

	}

}
 
Example 16
Source File: AbstractCache.java    From jetcache with Apache License 2.0 4 votes vote down vote up
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;
            }

        }
    }
}
 
Example 17
Source File: DataMovementServices.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
public void stopJob(Batcher batcher, ConcurrentHashMap<String, JobTicket> activeJobs) {
  if (batcher instanceof BatcherImpl) {
    ((BatcherImpl) batcher).stop();
  }
  if (batcher.getJobId() != null) activeJobs.remove(batcher.getJobId());
}
 
Example 18
Source File: DoubleKeyValueMap.java    From BigApp_Discuz_Android with Apache License 2.0 4 votes vote down vote up
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);
    }
}
 
Example 19
Source File: EditDataSet.java    From chart-fx with Apache License 2.0 4 votes vote down vote up
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));
                }
            }
        }
    }
}
 
Example 20
Source File: RebalanceLockManager.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
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);
    }
}