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

The following are Jave code examples for showing how to use remove() of the java.util.concurrent.ConcurrentHashMap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: jwx   File: TimeTest.java   View Source Code Vote up 7 votes
@Test
public void testMapClean() throws InterruptedException{
	ConcurrentHashMap<String, String> cache = new ConcurrentHashMap<String, String>();
	long lastCleanTimestamp = new Date().getTime();
	int cleanInterval = 2;
	cache.put("key1", "foo-" + new Date().getTime());
	Thread.sleep(500);
	cache.put("key2", "foo-" + new Date().getTime());
	Assert.assertEquals(cache.size(), 2);
	Thread.sleep(1700);
	long now = new Date().getTime();
	if((now-lastCleanTimestamp)/1000>=cleanInterval){
		lastCleanTimestamp = now;
		Iterator<Entry<String, String>> iter = cache.entrySet().iterator();
		while(iter.hasNext()){
			Entry<String, String> entry = iter.next();
			String key = entry.getKey();
			String value = entry.getValue();
			long valueTimestamp = Long.parseLong(value.substring(value.length()-13));
			if(valueTimestamp < now-cleanInterval*1000){
				cache.remove(key);
			}
		}
	}
	Assert.assertEquals(cache.size(), 1);
}
 
Example 2
Project: monarch   File: DiskInitFile.java   View Source Code Vote up 7 votes
public void cmnClearRegion(long drId,
    ConcurrentHashMap<DiskStoreID, RegionVersionHolder<DiskStoreID>> memberToVersion) {
  DiskRegionView drv = getDiskRegionById(drId);
  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 3
Project: NYBus   File: NYBusDriver.java   View Source Code Vote up 7 votes
/**
 * Remove method from methods map.
 *
 * @param mTargetMap      the target map.
 * @param targetObject    the target object.
 * @param targetChannelId the target channel ids.
 */
private void removeMethodFromMethodsMap(ConcurrentHashMap<Object,
        ConcurrentHashMap<String, SubscriberHolder>> mTargetMap,
                                        Object targetObject,
                                        List<String> targetChannelId) {
    ConcurrentHashMap<String, SubscriberHolder> mSubscribedMethodsMap =
            mTargetMap.get(targetObject);
    for (Map.Entry<String, SubscriberHolder> mSubscribedMethodsMapEntry :
            mSubscribedMethodsMap.entrySet()) {
        SubscriberHolder subscribedMethod = mSubscribedMethodsMapEntry.getValue();
        List<String> methodChannelId = subscribedMethod.subscribedChannelID;
        if (targetChannelId.containsAll(methodChannelId)) {
            mSubscribedMethodsMap.remove(mSubscribedMethodsMapEntry.getKey());
            removeTargetIfRequired(mSubscribedMethodsMap, mTargetMap, targetObject);
        }
    }
}
 
Example 4
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 7 votes
/**
 * SetValue of an EntrySet entry sets value in the map.
 */
public void testSetValueWriteThrough() {
    // Adapted from a bug report by Eric Zoerner
    ConcurrentHashMap map = new ConcurrentHashMap(2, 5.0f, 1);
    assertTrue(map.isEmpty());
    for (int i = 0; i < 20; i++)
        map.put(new Integer(i), new Integer(i));
    assertFalse(map.isEmpty());
    Map.Entry entry1 = (Map.Entry)map.entrySet().iterator().next();
    // Unless it happens to be first (in which case remainder of
    // test is skipped), remove a possibly-colliding key from map
    // which, under some implementations, may cause entry1 to be
    // cloned in map
    if (!entry1.getKey().equals(new Integer(16))) {
        map.remove(new Integer(16));
        entry1.setValue("XYZ");
        assertTrue(map.containsValue("XYZ")); // fails if write-through broken
    }
}
 
Example 5
Project: GitHub   File: DoubleKeyValueMap.java   View Source Code Vote up 6 votes
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);
    }
    if (k2_v == null || k2_v.isEmpty()) {
        k1_k2V_map.remove(key1);
    }
}
 
Example 6
Project: tomcat7   File: SlowQueryReport.java   View Source Code Vote up 6 votes
/**
 * Sort QueryStats by last invocation time
 * @param queries
 */
protected void removeOldest(ConcurrentHashMap<String,QueryStats> queries) {
    ArrayList<QueryStats> list = new ArrayList<QueryStats>(queries.values());
    Collections.sort(list, queryStatsComparator);
    int removeIndex = 0;
    while (queries.size() > maxQueries) {
        String sql = list.get(removeIndex).getQuery();
        queries.remove(sql);
        if (log.isDebugEnabled()) log.debug("Removing slow query, capacity reached:"+sql);
        removeIndex++;
    }
}
 
Example 7
Project: NYBus   File: NYBusDriver.java   View Source Code Vote up 6 votes
/**
 * Remove the target.
 *
 * @param subscribedMethods the subscribed methods.
 * @param mTargetMap        the target map.
 * @param targetObject      the target object.
 */
private void removeTargetIfRequired(ConcurrentHashMap<String, SubscriberHolder> subscribedMethods,
                                    ConcurrentHashMap<Object,
                                            ConcurrentHashMap<String, SubscriberHolder>> mTargetMap,
                                    Object targetObject) {
    if (subscribedMethods.size() == 0) {
        mTargetMap.remove(targetObject);
    }
}
 
Example 8
Project: jdk8u-jdk   File: ProtectionDomain.java   View Source Code Vote up 6 votes
/**
 * 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
Project: openjdk-jdk10   File: CleanerTest.java   View Source Code Vote up 6 votes
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 10
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 6 votes
/**
 * remove removes the correct key-value pair from the map
 */
public void testRemove() {
    ConcurrentHashMap map = map5();
    map.remove(five);
    assertEquals(4, map.size());
    assertFalse(map.containsKey(five));
}
 
Example 11
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 6 votes
/**
 * 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 12
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 6 votes
/**
 * remove(null) throws NPE
 */
public void testRemove1_NullPointerException() {
    ConcurrentHashMap c = new ConcurrentHashMap(5);
    c.put("sadsdf", "asdads");
    try {
        c.remove(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 13
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 6 votes
/**
 * remove(null, x) throws NPE
 */
public void testRemove2_NullPointerException() {
    ConcurrentHashMap c = new ConcurrentHashMap(5);
    c.put("sadsdf", "asdads");
    try {
        c.remove(null, "whatever");
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 14
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: RebalanceLockManager.java   View Source Code Vote up 5 votes
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);
    }
}
 
Example 15
Project: rmq4note   File: RebalanceLockManager.java   View Source Code Vote up 5 votes
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);
    }
}
 
Example 16
Project: reading-and-annotate-rocketmq-3.4.6   File: RebalanceLockManager.java   View Source Code Vote up 5 votes
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);
    }
}
 
Example 17
Project: metacom-android   File: AndroidJSTPConnection.java   View Source Code Vote up 5 votes
private boolean removeCachedCall(String cacheName, UUID uuid) {
    if (uuid == null) return false;
    ConcurrentHashMap<UUID, CacheCallData> cachedCalls = mTaggedCacheCalls.get(cacheName);
    return cachedCalls != null && cachedCalls.remove(uuid) != null;
}
 
Example 18
Project: pravega-samples   File: SharedMap.java   View Source Code Vote up 5 votes
@Override
public void process(ConcurrentHashMap<K, V> impl) {
    impl.remove(key);
}
 
Example 19
Project: Limitart   File: ScheduleTask.java   View Source Code Vote up 4 votes
@SuppressWarnings("unchecked")
@Override
public void execute(JobExecutionContext job) throws JobExecutionException {
	TriggerScheduleServiceCenterToProviderServiceCenterMessage msg = new TriggerScheduleServiceCenterToProviderServiceCenterMessage();
	String jobName = job.getJobDetail().getKey().getName();
	JobDataMap jobDataMap = job.getJobDetail().getJobDataMap();
	ConcurrentHashMap<Integer, ServiceXServerSession> rpcServers = (ConcurrentHashMap<Integer, ServiceXServerSession>) jobDataMap
			.get(RPCSERVERS);
	ConcurrentHashMap<String, ConcurrentHashSet<Integer>> schedules = (ConcurrentHashMap<String, ConcurrentHashSet<Integer>>) jobDataMap
			.get(SCHEDULES);
	ConcurrentHashSet<Integer> providerList = schedules.get(jobName);
	if (providerList == null) {
		log.error("Job:" + jobName + "找不到Provider");
		return;
	}
	msg.setJobName(jobName);
	// 查看是否是最有一次执行,并且移除此job
	if (!job.getTrigger().mayFireAgain()) {
		msg.setEnd(true);
		schedules.remove(jobName);
		log.info("任务生命终结,执行删除:" + jobName);
	}
	// 选举式触发
	ArrayList<Integer> arrayList = new ArrayList<>(providerList);
	int providerId = arrayList.get(RandomUtil.randomInt(0, arrayList.size() - 1));
	ServiceXServerSession serviceXServerSession = rpcServers.get(providerId);
	if (serviceXServerSession != null) {
		serviceXServerSession.getSession().writeAndFlush(msg);
		log.info(jobName + "触发!分配的ProviderId为:" + providerId + ",下次触发时间:"
				+ TimeUtil.date2Str(job.getTrigger().getNextFireTime().getTime()));
	}
}
 
Example 20
Project: jsf-sdk   File: TwoLevelMap.java   View Source Code Vote up 3 votes
/**
 * 删除二级key
 *
 * @param parentKey
 *         一级key
 * @param childKey
 *         二级key
 * @return 删除结果
 */
public V remove(K parentKey, K childKey) {
    ConcurrentHashMap<K, V> map = get(parentKey);
    return map != null ? map.remove(childKey) : null;
}