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

The following are Jave code examples for showing how to use size() 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: tomcat7   File: SlowQueryReport.java   View Source Code Vote up 8 votes
protected QueryStats getQueryStats(String sql) {
    if (sql==null) sql = "";
    ConcurrentHashMap<String,QueryStats> queries = SlowQueryReport.this.queries;
    if (queries==null) {
        if (log.isWarnEnabled()) log.warn("Connection has already been closed or abandoned");
        return null;
    }
    QueryStats qs = queries.get(sql);
    if (qs == null) {
        qs = new QueryStats(sql);
        if (queries.putIfAbsent(sql,qs)!=null) {
            qs = queries.get(sql);
        } else {
            //we added a new element, see if we need to remove the oldest
            if (queries.size() > maxQueries) {
                removeOldest(queries);
            }
        }
    }
    return qs;
}
 
Example 2
Project: monarch   File: AutoSerializableJUnitTest.java   View Source Code Vote up 7 votes
@Override
public Object writeTransform(Field f, Class<?> clazz, Object originalValue) {
  if (f.getType().equals(ConcurrentHashMap.class)) {
    Object[] result = null;
    if (originalValue != null) {
      ConcurrentHashMap<?, ?> m = (ConcurrentHashMap<?, ?>) originalValue;
      result = new Object[m.size() * 2];
      int i = 0;
      for (Map.Entry<?, ?> e : m.entrySet()) {
        result[i++] = e.getKey();
        result[i++] = e.getValue();
      }
    }
    return result;
  } else {
    return super.writeTransform(f, clazz, originalValue);
  }
}
 
Example 3
Project: apache-tomcat-7.0.73-with-comment   File: SlowQueryReport.java   View Source Code Vote up 7 votes
protected QueryStats getQueryStats(String sql) {
    if (sql==null) sql = "";
    ConcurrentHashMap<String,QueryStats> queries = SlowQueryReport.this.queries;
    if (queries==null) {
        if (log.isWarnEnabled()) log.warn("Connection has already been closed or abandoned");
        return null;
    }
    QueryStats qs = queries.get(sql);
    if (qs == null) {
        qs = new QueryStats(sql);
        if (queries.putIfAbsent(sql,qs)!=null) {
            qs = queries.get(sql);
        } else {
            //we added a new element, see if we need to remove the oldest
            if (queries.size() > maxQueries) {
                removeOldest(queries);
            }
        }
    }
    return qs;
}
 
Example 4
Project: GitHub   File: DoubleKeyValueMap.java   View Source Code Vote up 6 votes
public int size() {
    if (k1_k2V_map.size() == 0) return 0;

    int result = 0;
    for (ConcurrentHashMap<K2, V> k2V_map : k1_k2V_map.values()) {
        result += k2V_map.size();
    }
    return result;
}
 
Example 5
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 6
Project: CrypDist   File: HeartBeatTask.java   View Source Code Vote up 6 votes
public HeartBeatTask(Client client, ConcurrentHashMap<Peer,Integer> peerList, int hbPort, int swPort) {
    this.peerList = peerList;
    this.hbPort = hbPort;
    this.swPort = swPort;
    this.size =peerList.size();
    HeartBeatTask.client = client;
}
 
Example 7
Project: apache-tomcat-7.0.73-with-comment   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 8
Project: jdk8u-jdk   File: HelloImpl.java   View Source Code Vote up 6 votes
@Override
public String sayHelloWithHashMap(ConcurrentHashMap<String, String> receivedHashMap)
        throws RemoteException {
    int hashMapSize = 0;

    hashMapSize = receivedHashMap.size();
    String response = "Hello with hashMapSize == " + hashMapSize;
    return response;
}
 
Example 9
Project: openjdk-jdk10   File: CleanerTest.java   View Source Code Vote up 6 votes
/**
 * Example using a Cleaner to remove WeakKey references from a Map.
 */
@Test
void testWeakKey() {
    ConcurrentHashMap<WeakKey<String>, String> map = new ConcurrentHashMap<>();
    Cleaner cleaner = Cleaner.create();
    String key = new String("foo");  //  ensure it is not interned
    String data = "bar";

    map.put(new WeakKey<>(key, cleaner, map), data);

    WeakKey<String> k2 = new WeakKey<>(key, cleaner, map);

    Assert.assertEquals(map.get(k2), data, "value should be found in the map");
    key = null;
    System.gc();
    Assert.assertNotEquals(map.get(k2), data, "value should not be found in the map");

    final long CYCLE_MAX = Utils.adjustTimeout(30L);
    for (int i = 1; map.size() > 0 && i < CYCLE_MAX; i++) {
        map.forEach( (k, v) -> System.out.printf("    k: %s, v: %s%n", k, v));
        try {
            Thread.sleep(10L);
        } catch (InterruptedException ie) {}
    }
    Assert.assertEquals(map.size(), 0, "Expected map to be empty;");
    cleaner = null;
}
 
Example 10
Project: openjdk-jdk10   File: HelloImpl.java   View Source Code Vote up 6 votes
@Override
public String sayHelloWithHashMap(ConcurrentHashMap<String, String> receivedHashMap)
        throws RemoteException {
    int hashMapSize = 0;

    hashMapSize = receivedHashMap.size();
    String response = "Hello with hashMapSize == " + hashMapSize;
    return response;
}
 
Example 11
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 12
Project: NYBus   File: NYBusDriver.java   View Source Code Vote up 6 votes
/**
 * Remove the event.
 *
 * @param mTargetMap               the target map.
 * @param mEventsToTargetsMapEntry the event to target map entry.
 */
private void removeEventIfRequired(ConcurrentHashMap<Object,
        ConcurrentHashMap<String, SubscriberHolder>> mTargetMap,
                                   Map.Entry<Class<?>, ConcurrentHashMap<Object,
                                           ConcurrentHashMap<String,
                                                   SubscriberHolder>>> mEventsToTargetsMapEntry) {
    if (mTargetMap.size() == 0) {
        mEventsToTargetsMap.remove(mEventsToTargetsMapEntry.getKey());
    }
}
 
Example 13
Project: alfresco-repository   File: ReferenceCountingReadOnlyIndexReaderFactory.java   View Source Code Vote up 5 votes
private <T> T manageCache(ConcurrentHashMap<Integer, WithUseCount<T>> cache, Accessor<T> accessor, int n, FieldSelector fieldSelector, int limit) throws IOException
{
    Integer key = Integer.valueOf(n);
    WithUseCount<T> value = cache.get(key);
    if (value == null)
    {
        T made = accessor.get(n, fieldSelector);
        value = new WithUseCount<T>(made, n);
        cache.put(key, value);

        // resize

        if (limit >= 0)
        {
            if (cache.size() >= limit)
            {
                HashMap<Integer, WithUseCount<T>> keep = new HashMap<Integer, WithUseCount<T>>();
                WithUseCount<T>[] existing = new WithUseCount[0];
                synchronized (cache)
                {
                    existing = cache.values().toArray(existing);
                    cache.clear();
                }
                Arrays.sort(existing);

                for (WithUseCount<T> current : existing)
                {
                    keep.put(Integer.valueOf(current.doc), current);
                    if ((current.count.get() == 0) || (keep.size() > (limit / 4)))
                    {
                        break;
                    }
                }
                keep.put(key, value);
                cache.putAll(keep);
            }
        }
    }
    else
    {
        value.count.getAndIncrement();
    }
    return value.object;
}
 
Example 14
Project: think-in-java   File: ConcurrentHashMapTest.java   View Source Code Vote up 5 votes
public static void main(String[] args) {
    ConcurrentHashMap map = new ConcurrentHashMap();
    map.put(1,2);
    map.get(1);
    map.size();
}
 
Example 15
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();
    }
}