ConcurrentHashMap 线程安全问题
public class Main {
private static int THREAD_COUNT = 10;
private static int ITEM_COUNT = 1000;
private static ConcurrentHashMap<String, Long> getData(int count) {
return LongStream.rangeClosed(1, count)
.boxed().collect(Collectors.toConcurrentMap(i-> UUID.randomUUID().toString(), Function.identity(),(t1, t2)->t1,ConcurrentHashMap::new));
}
public static void main(String[] args) throws InterruptedException {
ConcurrentHashMap<String, Long> stringLongConcurrentHashMap = getData(ITEM_COUNT-100);
System.out.println("init siez:"+stringLongConcurrentHashMap.size());
ForkJoinPool forkJoinPool = new ForkJoinPool(THREAD_COUNT);
forkJoinPool.execute(()-> IntStream.rangeClosed(1,10).parallel().forEach(i->{
int gap=ITEM_COUNT-stringLongConcurrentHashMap.size();
System.out.println("gap siez:"+gap);
stringLongConcurrentHashMap.putAll(getData(gap));
}));
forkJoinPool.shutdown();
forkJoinPool.awaitTermination(1, TimeUnit.HOURS);
System.out.println("finish siez:"+stringLongConcurrentHashMap.size());
}
}
上面没添加锁输出以下结果
init siez:900
gap siez:100
gap siez:100
gap siez:100
gap siez:100
gap siez:100
gap siez:100
gap siez:100
gap siez:100
gap siez:100
gap siez:100
finish siez:1900
添加锁之后
public class Main {
private static int THREAD_COUNT = 10;
private static int ITEM_COUNT = 1000;
private static ConcurrentHashMap<String, Long> getData(int count) {
return LongStream.rangeClosed(1, count)
.boxed().collect(Collectors.toConcurrentMap(i-> UUID.randomUUID().toString(), Function.identity(),(t1, t2)->t1,ConcurrentHashMap::new));
}
public static void main(String[] args) throws InterruptedException {
ConcurrentHashMap<String, Long> stringLongConcurrentHashMap = getData(ITEM_COUNT-100);
System.out.println("init siez:"+stringLongConcurrentHashMap.size());
ForkJoinPool forkJoinPool = new ForkJoinPool(THREAD_COUNT);
forkJoinPool.execute(()-> IntStream.rangeClosed(1,10).parallel().forEach(i->{
synchronized (stringLongConcurrentHashMap){
int gap=ITEM_COUNT-stringLongConcurrentHashMap.size();
System.out.println("gap siez:"+gap);
stringLongConcurrentHashMap.putAll(getData(gap));
}
}));
forkJoinPool.shutdown();
forkJoinPool.awaitTermination(1, TimeUnit.HOURS);
System.out.println("finish siez:"+stringLongConcurrentHashMap.size());
}
}
输出结果
init siez:900
gap siez:100
gap siez:0
gap siez:0
gap siez:0
gap siez:0
gap siez:0
gap siez:0
gap siez:0
gap siez:0
gap siez:0
finish siez:1000