I have an array of Objects which I stream to use a function on each object to modify it and add it to a completely new array of Objects.
By using .parallel() the execution time speeds up 2 times, but I'm getting some NullPointerExceptions when looping over the new array.
I tried to debug it a few times without any success. It seems that this problem only occurs during the runtime. I tried implementing a synchronized function for adding the new objects to the list, but sadly it didn't work as well.
Can anyone give me a suggestion how to get this working? Thanks in advance!
Here is the code snippet:
private static final Object sync = new Object();
private ArrayList<Object> newList = new ArrayList<Object>();
private void addNewObject(Object newObject) {
synchronized (sync) {
newList.add(newObject);
}
}
private Object mutateObject(Object oldObject) {
// Do something with the object here
return mutatedObject;
}
public ArrayList<Object> createNewList(ArrayList<Object> oldList) {
oldList.stream().parallel().forEach(object -> addNewObject(mutateObject(object)));
return newList;
}
List<Object>for your public interface instead of implementations like ArrayList