关于ConcurrentHashMap
在并发编程中,经常会用到ConcurrentHashMap,因为HashMap是非线程安全的,而ConcurrentHashMap是线程安全的。项目中通常会对ConcurrentHashMap进行封装,此时就会涉及到对ConcurrentHashMap扩容的操作。
代码实现:
<pre>
import java.util.concurrent.ConcurrentHashMap;
/**
-
Created by lenvovo on 2016/9/23.
*/
public class TestCopy {public static ConcurrentHashMap<String,String> names = new ConcurrentHashMap<>(6666);
static {
for(int i=0;i<18;i++){
names.put("jack"+i,"jacklee"+i);
}
}
public static void main(String []args){
ConcurrentHashMap<String,String> copy_names = new ConcurrentHashMap<>(88888);
for(ConcurrentHashMap.Entry<String,String> name:names.entrySet()){
System.out.println(name.getKey()+'\t'+name.getValue());
copy_names.put(name.getKey(),name.getValue());} System.out.println("nmaes size -----:"+names.size());//返回的是含有数据的大小-->18,而不是容量大小 System.out.println("nmaes size -----:"+copy_names.size()); for(ConcurrentHashMap.Entry<String,String> copy_name:copy_names.entrySet()){ System.out.println(copy_name.getKey()+'\t'+copy_name.getValue()); }
}
}
</pre>
经测试,以上代码能实现ConcurrentHashMap数据的复制,即能实现ConcurrentHashMap的扩容。
参考:
网友评论