1. 那么ConcurrentHashMap是如何判断在统计的时候容器是否发生了变化呢?使用modCount变量,在put、 remove 和clean
方法里操作元素前都会将变量modCount进行加1,那么在统计size前后比较modCount是否发生变化,从而得知容器的大小
是否发生变化。
2. 关于该类中一些方法的测试:
parallelismThreshold
参数,如果map的size小于给的阈值,则使用Long.MAX_VALUE
作为最大并发量;如果设置为1,则产生足够多的子任务来并发执行
search方法,要注意一点
//concurrentHashMap<String,Integer>
public void testSearch(){
Boolean find = concurrentHashMap.search(10,(k,v)->{
if(k=="zlz" && v==21)
return Boolean.TRUE;
//注意:如果一个entry中未找到就返回null,然后继续遍历,否则会提前中断遍历
return null;
});
System.out.println(find);
if(find) System.out.println("zlz 21 exist");
else System.out.println("zlz 21 not exist");
}
reduceValuesToInt
public void testReduceValuesToInt(){
int result = concurrentHashMap.reduceValuesToInt(10,i->i*i,0,(x,y)->x+y);
System.out.println(result);
}
NewKeySet:都说是相当于并行集合,相比较于keyset多了add方法。函数得到的set是空的。
public void testNewKeySet(){
Set<String> set = concurrentHashMap.newKeySet();
//下面注释掉的代码是不能用的,会报错,也说明它是只读的
//concurrentHashMap.keySet().add("zzz");
set.forEach(System.out::println);
concurrentHashMap.keySet().forEach(element->{
set.add(element);
});
set.forEach(System.out::println);
}
merge:merge(key,newValue,Bifunction())
// 其中BiFunction的两个输入的顺序(oldValue,newValue)
// BiFunction的输出为最终的value
public void testMerge(){
int result = concurrentHashMap.merge("zlz",25,(v1,v2)->v1+v2);
//v1+v2会代替原来的值
System.out.println(result);
}
顺便说一嘴,在熟悉测试某个类的方法时,可以用test****的命名方法,然后用反射自动测试,当然有的需要测试的方法是有参数的,这个时候,你在测试函数里面填一下测试方法呗。
主要代码如下,挺简单的,但是很好用
//tch是testConcurrentHashMap的实例对象,自己用的时候用自己的对象代替
Method[] methods = tch.getClass().getMethods();
for(Method method : methods){
if(method.getName().contains("test")){
System.out.println(method.getName());
method.invoke(tch,null);
System.out.println("--------------------------------------------------------");
}
}