I have a null pointer exception because adPicsthere are several null values in the list . This rarely happens. How is this possible?
(This code loads images in parallel and saves them locally.)
List<String> downloadAdImages(List<String> imagesUrls, final String itemFolder) {
final List adPics = new ArrayList<>();
final ExecutorService executor = newFixedThreadPool(20);
imagesUrls.forEach(
picUrl -> executor.submit(() -> {
try {
String imageNewFileName = imagesUrls.indexOf(picUrl) + "." + getExtension(picUrl);
String bigPicUrl = picUrl.replace("b.jpg", "ab.jpg");
copyURLToFile(new URL(bigPicUrl), new File(itemFolder, imageNewFileName), 10, 10);
adPics.add(imageNewFileName);
} catch (IOException ex) {
log.log(Level.WARNING, "Could not download image {0} ({1})", new Object[]{picUrl, ex.getMessage()});
}
}));
executor.shutdown();
try {
executor.awaitTermination(15L, MILLISECONDS);
} catch (InterruptedException ex) {
log.log(Level.WARNING, "Could not wait for all images downloads");
}
Collections.sort(adPics);
return adPics;
}

Sometimes adPicsit matters null. It is for this reason that NPE. But how? By analyzing the code executed in the thread, it is impossible to add a value null. If there is a problem loading the image, it will throw an IOException. imageNewFileNamecannot be null.
This code is Java 8 and uses the Apache Commons IO lib.
source
share