Careful with Parallel Streams in java 8
List<String> list = new ArrayList<String>(); //contains about 1000 element
List<String> listA = new ArrayList<String>(); // zezo element now
List<String> listB = new ArrayList<String>(); //zezo element now
list.parallelStream().forEach(e -> { if (e.equals("A")) { listA.add(e); } else { listB.add(e); } });
list.stream().forEach(e -> { if (e.equals("A")) { listA.add(e); } else { listB.add(e); } });
Maybe some guys will think that the above codes with parallelStream() is faster and better than the code with stream()
If you try to run it in fact with parallelStream() then it may throw IndexOutOfArrayException, but with stream() is well.
Why?????
1. listA.add(e); and listB.add() is not supported using in mutilthread. Your code is not good
2. why it throw IndexOutOfArrayException? please read codes of ArrayList :-)
Note:
1. you should use
.synchronizedList(list);
So you can use synlist in multithread
2. Only use list.get() in multithread, the function is thread safe
very useful!!!
ReplyDelete