Very strange NullPointerException on sorting

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"); // 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;
   }

Stack Trace ## Header ##

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.

+4
source share
2

awaitTermination . timeout. - .

, , -.

, , - , .

. .

+2

. . , List adPics.

, [CompletableFuture] CompletableFuture.allOf. CompletableFuture , , , . , CompletableFuture . CompletableFuture.allOf .

0

Source: https://habr.com/ru/post/1650956/


All Articles