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  
List<String> synlist = Collections.synchronizedList(list);

So you can use synlist in multithread


2. Only use list.get() in multithread, the function is thread safe















Comments

Post a Comment

Popular posts from this blog

Fixing the DeepSpeed Import Error While Fine-Tuning the Qwen Model

Amazon Linux 2023 - User data configuration for launch templates to connect to the EKS cluster

How to create ISM policy and rotate logs in opensearch