I have a null pointer exception because there's some null values at the list adPics
. It happens rarely. How is it possible?
(This code downloads 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"); // big version
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); // null values at list lead to NPE here. How are there null values?
return adPics;
}
Sometimes adPics
list has null
values. That is the reason for the NPE. But how? Analysing the code executed in the thread, it can't be possible to add a null
value. If there was problem downloading the image, it would thrown a IOException. imageNewFileName
can't be null
.
This code is Java 8 and it uses Apache Commons IO lib.