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

The following are Jave code examples for showing how to use keySet() 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: GitHub   File: SPCookieStore.java   View Source Code Vote up 7 votes
@Override
public synchronized boolean removeCookie(HttpUrl url) {
    if (!cookies.containsKey(url.host())) return false;

    //内存移除
    ConcurrentHashMap<String, Cookie> urlCookie = cookies.remove(url.host());
    //文件移除
    Set<String> cookieTokens = urlCookie.keySet();
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    for (String cookieToken : cookieTokens) {
        if (cookiePrefs.contains(COOKIE_NAME_PREFIX + cookieToken)) {
            prefsWriter.remove(COOKIE_NAME_PREFIX + cookieToken);
        }
    }
    prefsWriter.remove(url.host());
    prefsWriter.apply();

    return true;
}
 
Example 2
Project: reading-and-annotate-rocketmq-3.4.6   File: DefaultMQPullConsumerImpl.java   View Source Code Vote up 7 votes
public Set<MessageQueue> fetchMessageQueuesInBalance(String topic) throws MQClientException {
    this.makeSureStateOK();
    if (null == topic) {
        throw new IllegalArgumentException("topic is null");
    }

    ConcurrentHashMap<MessageQueue, ProcessQueue> mqTable = this.rebalanceImpl.getProcessQueueTable();
    Set<MessageQueue> mqResult = new HashSet<MessageQueue>();
    for (MessageQueue mq : mqTable.keySet()) {
        if (mq.getTopic().equals(topic)) {
            mqResult.add(mq);
        }
    }

    return mqResult;
}
 
Example 3
Project: XinFramework   File: SPCookieStore.java   View Source Code Vote up 7 votes
@Override
public synchronized boolean removeCookie(HttpUrl url) {
    if (!cookies.containsKey(url.host())) return false;

    //内存移除
    ConcurrentHashMap<String, Cookie> urlCookie = cookies.remove(url.host());
    //文件移除
    Set<String> cookieTokens = urlCookie.keySet();
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    for (String cookieToken : cookieTokens) {
        if (cookiePrefs.contains(COOKIE_NAME_PREFIX + cookieToken)) {
            prefsWriter.remove(COOKIE_NAME_PREFIX + cookieToken);
        }
    }
    prefsWriter.remove(url.host());
    prefsWriter.apply();

    return true;
}
 
Example 4
Project: TPlayer   File: SPCookieStore.java   View Source Code Vote up 7 votes
@Override
public synchronized boolean removeCookie(HttpUrl url) {
    if (!cookies.containsKey(url.host())) {
        return false;
    }

    //内存移除
    ConcurrentHashMap<String, Cookie> urlCookie = cookies.remove(url.host());
    //文件移除
    Set<String> cookieTokens = urlCookie.keySet();
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    for (String cookieToken : cookieTokens) {
        if (cookiePrefs.contains(COOKIE_NAME_PREFIX + cookieToken)) {
            prefsWriter.remove(COOKIE_NAME_PREFIX + cookieToken);
        }
    }
    prefsWriter.remove(url.host());
    prefsWriter.apply();

    return true;
}
 
Example 5
Project: openjdk-jdk10   File: ConcurrentHashMap8Test.java   View Source Code Vote up 7 votes
/**
 * keySet.add adds the key with the established value to the map;
 * remove removes it.
 */
public void testKeySetAddRemove() {
    ConcurrentHashMap map = map5();
    Set set1 = map.keySet();
    Set set2 = map.keySet(true);
    set2.add(six);
    assertSame(map, ((ConcurrentHashMap.KeySetView)set2).getMap());
    assertSame(map, ((ConcurrentHashMap.KeySetView)set1).getMap());
    assertEquals(set2.size(), map.size());
    assertEquals(set1.size(), map.size());
    assertTrue((Boolean)map.get(six));
    assertTrue(set1.contains(six));
    assertTrue(set2.contains(six));
    set2.remove(six);
    assertNull(map.get(six));
    assertFalse(set1.contains(six));
    assertFalse(set2.contains(six));
}
 
Example 6
Project: openjdk-jdk10   File: ConcurrentHashMap8Test.java   View Source Code Vote up 7 votes
/**
 * KeySetView.getMappedValue returns the map's mapped value
 */
public void testGetMappedValue() {
    ConcurrentHashMap map = map5();
    assertNull(map.keySet().getMappedValue());
    try {
        map.keySet(null);
        shouldThrow();
    } catch (NullPointerException success) {}
    ConcurrentHashMap.KeySetView set = map.keySet(one);
    assertFalse(set.add(one));
    assertTrue(set.add(six));
    assertTrue(set.add(seven));
    assertSame(one, set.getMappedValue());
    assertNotSame(one, map.get(one));
    assertSame(one, map.get(six));
    assertSame(one, map.get(seven));
}
 
Example 7
Project: rmq4note   File: DefaultMQPullConsumerImpl.java   View Source Code Vote up 7 votes
public Set<MessageQueue> fetchMessageQueuesInBalance(String topic) throws MQClientException {
    this.makeSureStateOK();
    if (null == topic) {
        throw new IllegalArgumentException("topic is null");
    }

    ConcurrentHashMap<MessageQueue, ProcessQueue> mqTable = this.rebalanceImpl.getProcessQueueTable();
    Set<MessageQueue> mqResult = new HashSet<MessageQueue>();
    for (MessageQueue mq : mqTable.keySet()) {
        if (mq.getTopic().equals(topic)) {
            mqResult.add(mq);
        }
    }

    return mqResult;
}
 
Example 8
Project: SuperHttp   File: SPCookieStore.java   View Source Code Vote up 7 votes
@Override
public synchronized boolean removeCookie(HttpUrl url) {
    if (!cookies.containsKey(url.host())) return false;

    //内存移除
    ConcurrentHashMap<String, Cookie> urlCookie = cookies.remove(url.host());
    //文件移除
    Set<String> cookieTokens = urlCookie.keySet();
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    for (String cookieToken : cookieTokens) {
        if (cookiePrefs.contains(COOKIE_NAME_PREFIX + cookieToken)) {
            prefsWriter.remove(COOKIE_NAME_PREFIX + cookieToken);
        }
    }
    prefsWriter.remove(url.host());
    prefsWriter.apply();

    return true;
}
 
Example 9
Project: ditb   File: IntegrationTestDDLMasterFailover.java   View Source Code Vote up 7 votes
protected HTableDescriptor selectTable(ConcurrentHashMap<TableName, HTableDescriptor> tableMap)
{
  // randomly select table from tableMap
  if (tableMap.isEmpty()){
    return null;
  }
  // synchronization to prevent removal from multiple threads
  synchronized (tableMap){
    ArrayList<TableName> tableList = new ArrayList<TableName>(tableMap.keySet());
    TableName randomKey = tableList.get(RandomUtils.nextInt(tableList.size()));
    HTableDescriptor randomHtd = tableMap.get(randomKey);
    // remove from tableMap
    tableMap.remove(randomKey);
    return randomHtd;
  }
}
 
Example 10
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 6 votes
/**
 * keySet returns a Set containing all the keys
 */
public void testKeySet() {
    ConcurrentHashMap map = map5();
    Set s = map.keySet();
    assertEquals(5, s.size());
    assertTrue(s.contains(one));
    assertTrue(s.contains(two));
    assertTrue(s.contains(three));
    assertTrue(s.contains(four));
    assertTrue(s.contains(five));
}
 
Example 11
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 6 votes
/**
 * Test keySet().removeAll on empty map
 */
public void testKeySet_empty_removeAll() {
    ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();
    Set<Integer> set = map.keySet();
    set.removeAll(Collections.emptyList());
    assertTrue(map.isEmpty());
    assertTrue(set.isEmpty());
    // following is test for JDK-8163353
    set.removeAll(Collections.emptySet());
    assertTrue(map.isEmpty());
    assertTrue(set.isEmpty());
}
 
Example 12
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 6 votes
/**
 * keySet.toArray returns contains all keys
 */
public void testKeySetToArray() {
    ConcurrentHashMap map = map5();
    Set s = map.keySet();
    Object[] ar = s.toArray();
    assertTrue(s.containsAll(Arrays.asList(ar)));
    assertEquals(5, ar.length);
    ar[0] = m10;
    assertFalse(s.containsAll(Arrays.asList(ar)));
}
 
Example 13
Project: tqdev-metrics   File: MetricRegistry.java   View Source Code Vote up 6 votes
/**
 * Gets the (unique) set of keys of all registered metrics of a given type.
 *
 * @param type
 *            the type
 * @return the keys
 */
public Iterable<String> getKeys(String type) {
	ConcurrentHashMap<String, Object> map = values.get(type);
	if (map == null) {
		return emptySet();
	}
	return map.keySet();
}
 
Example 14
Project: alfresco-solrclient   File: TrackerStats.java   View Source Code Vote up 5 votes
/**
 * @param all ConcurrentHashMap<String, IncrementalStats>
 * @return SimpleStats
 */
private SimpleStats aggregateResults(ConcurrentHashMap<String, IncrementalStats> all)
{
    SimpleStats answer = null;

    for (String key : all.keySet())
    {
        IncrementalStats next = all.get(key);
        IncrementalStats stats = next.copy();
        if (answer == null)
        {
            answer = new SimpleStats(stats.scale, this.infoSrv);
            answer .start  = stats.start;
            answer.moments[0] = stats.moments[0];
            answer.moments[1] = stats.moments[1];
            answer.moments[2] = stats.moments[2];
            answer.max = stats.max;
            answer.min = stats.min;
            answer.copies.put(key, stats);
        }
        else
        {
            SimpleStats newAnswer = new SimpleStats(answer.scale, this.infoSrv);

            newAnswer.moments[0] = answer.moments[0] + stats.moments[0];

            newAnswer.moments[1] = answer.moments[1] * answer.moments[0] + stats.moments[1] * stats.moments[0];
            newAnswer.moments[1] /= answer.moments[0] + stats.moments[0];

            newAnswer.moments[2] = answer.moments[2] * answer.moments[0];
            newAnswer.moments[2] += (answer.moments[1] - newAnswer.moments[1]) * (answer.moments[1] - newAnswer.moments[1]) * answer.moments[0];
            newAnswer.moments[2] += stats.moments[2] * stats.moments[0];
            newAnswer.moments[2] += (stats.moments[1] - newAnswer.moments[1]) * (stats.moments[1] - newAnswer.moments[1]) * stats.moments[0];
            newAnswer.moments[2] /= answer.moments[0] + stats.moments[0];

            newAnswer.min = (stats.min < answer.min) ? stats.min : answer.min;
            newAnswer.max = (stats.max > answer.max) ? stats.max : answer.max;
            
            newAnswer.start = (stats.start.compareTo(answer.start) < 1) ? stats.start : answer.start;

            newAnswer.copies.putAll(answer.copies);
            newAnswer.copies.put(key, stats);

            answer = newAnswer;
        }

    }

    if (answer == null)
    {
        answer = new SimpleStats(1, this.infoSrv);
    }

    return answer;
}
 
Example 15
Project: jsf-sdk   File: ConnectionHolder.java   View Source Code Vote up 5 votes
/**
 * 存活的全部provider
 *
 * @return all alive providers
 */
public List<Provider> getAliveProviders() {
    ConcurrentHashMap<Provider, ClientTransport> map =
            aliveConnections.isEmpty() ? subHealthConnections : aliveConnections;
    return new ArrayList<Provider>(map.keySet());
}
 
Example 16
Project: Higher-Cloud-Computing-Project   File: KMeansDistributedClusterer.java   View Source Code Vote up 5 votes
/** Initialize cluster centers. */
private Vector[] initClusterCenters(SparseDistributedMatrix points, int k) {
    // Initialize empty centers and point costs.
    int ptsCnt = points.rowSize();

    String cacheName = ((SparseDistributedMatrixStorage)points.getStorage()).cacheName();

    // Initialize the first center to a random point.
    Vector sample = localCopyOf(points.viewRow(rnd.nextInt(ptsCnt)));

    List<Vector> centers = new ArrayList<>();
    List<Vector> newCenters = new ArrayList<>();
    newCenters.add(sample);
    centers.add(sample);

    final ConcurrentHashMap<Integer, Double> costs = new ConcurrentHashMap<>();

    // On each step, sample 2 * k points on average with probability proportional
    // to their squared distance from the centers. Note that only distances between points
    // and new centers are computed in each iteration.
    int step = 0;
    UUID uid = points.getUUID();

    while (step < initSteps) {
        // We assume here that costs can fit into memory of one node.
        ConcurrentHashMap<Integer, Double> newCosts = getNewCosts(points, newCenters, cacheName);

        // Merge costs with new costs.
        for (Integer ind : newCosts.keySet())
            costs.merge(ind, newCosts.get(ind), Math::min);

        double sumCosts = costs.values().stream().mapToDouble(Double::valueOf).sum();

        newCenters = getNewCenters(k, costs, uid, sumCosts, cacheName);
        centers.addAll(newCenters);

        step++;
    }

    List<Vector> distinctCenters = centers.stream().distinct().collect(Collectors.toList());

    if (distinctCenters.size() <= k)
        return distinctCenters.toArray(new Vector[] {});
    else {
        // Finally, we might have a set of more than k distinct candidate centers; weight each
        // candidate by the number of points in the dataset mapping to it and run a local k-means++
        // on the weighted centers to pick k of them
        ConcurrentHashMap<Integer, Integer> centerInd2Weight = weightCenters(uid, distinctCenters, cacheName);

        List<Double> weights = new ArrayList<>(centerInd2Weight.size());

        for (int i = 0; i < distinctCenters.size(); i++)
            weights.add(i, Double.valueOf(centerInd2Weight.getOrDefault(i, 0)));

        DenseLocalOnHeapMatrix dCenters = MatrixUtil.fromList(distinctCenters, true);

        return new KMeansLocalClusterer(getDistanceMeasure(), 30, seed).cluster(dCenters, k, weights).centers();
    }
}
 
Example 17
Project: blueirisviewer   File: ByteArrayPool.java   View Source Code Vote up 5 votes
private static void cleanup(ConcurrentHashMap<Integer, ConcurrentLinkedQueue<byte[]>> pool)
{
	for (int key : pool.keySet())
		cleanup(pool.get(key));
}
 
Example 18
Project: crawler   File: MonitorServlet.java   View Source Code Vote up 5 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
	String method=req.getParameter("method");
	String name=req.getParameter("name");
	String uri=req.getRequestURI();
	if(StringUtils.isBlank(method)){
		List<Map<String, String>> infolist = new ArrayList<>();
		ConcurrentHashMap<String, Spider> spiders = SpiderManager.get()
				.getSpiders();
		for (String key : spiders.keySet()) {
			Map<String, String> map = new HashMap<>();
			Spider spider = spiders.get(key);
			map.put("name", key);
			map.put("processor", spider.getProcessor().getClass().getName());
			map.put("status", spider.getState().name().toLowerCase());
			SimpleDateFormat sdf = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			Date start = spider.getStartTime();
			Date end = spider.getEndTime();
			end = end == null ? new Date() : end;
			long runsecs = start == null ? 0 : (end.getTime() - start
					.getTime()) / 1000;
			map.put("info",
					"开始时间:"
							+ (start == null ? "无" : sdf.format(start))
							+ ",运行时间:"
							+ runsecs
							+ "秒,"
							+ "总请求数:"
							+ spider.getScheduler().getTotalRequestsCount(
									spider)
							+ ",剩余请求数:"
							+ spider.getScheduler().getLeftRequestsCount(
									spider));

			infolist.add(map);
		}
		req.setAttribute("root", req.getServletContext().getContextPath());
		req.setAttribute("spiders", infolist);
		req.getRequestDispatcher("/jsp/spider-list.jsp").forward(req, resp);
	}else if(method.equals("start")){
		outString(resp, String.valueOf(SpiderManager.get().start(name)));
	}else if(method.equals("stop")){
		outString(resp, String.valueOf(SpiderManager.get().stop(name)));
	}
}
 
Example 19
Project: Higher-Cloud-Computing-Project   File: FuzzyCMeansDistributedClusterer.java   View Source Code Vote up 4 votes
/**
 * Choose k primary centers from source points.
 *
 * @param points Matrix with source points.
 * @param k Number of centers.
 * @return Array of primary centers.
 */
private Vector[] initializeCenters(SparseDistributedMatrix points, int k) {
    int pointsNum = points.rowSize();

    Vector firstCenter = points.viewRow(rnd.nextInt(pointsNum));

    List<Vector> centers = new ArrayList<>();
    List<Vector> newCenters = new ArrayList<>();

    centers.add(firstCenter);
    newCenters.add(firstCenter);

    ConcurrentHashMap<Integer, Double> costs = new ConcurrentHashMap<>();

    int step = 0;
    UUID uuid = points.getUUID();
    String cacheName = ((SparseDistributedMatrixStorage) points.getStorage()).cacheName();

    while(step < initSteps) {
        ConcurrentHashMap<Integer, Double> newCosts = getNewCosts(cacheName, uuid, newCenters);

        for (Integer key : newCosts.keySet())
            costs.merge(key, newCosts.get(key), Math::min);

        double costsSum = costs.values().stream().mapToDouble(Double::valueOf).sum();

        newCenters = getNewCenters(cacheName, uuid, costs, costsSum, k);
        centers.addAll(newCenters);

        step++;
    }

    return chooseKCenters(cacheName, uuid, centers, k);
}