LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Concurrency and Executors Programs · Question 1

Process files in parallel with a thread pool in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Simulate generating thumbnails for 8 images on a fixed pool of 4 threads (each takes 50 ms); collect each image's thumbnail size through Futures in order and print the results and total.

Solution
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
    static int makeThumbnail(String file) throws InterruptedException {
        Thread.sleep(50);                                  // pretend to resize the image
        return file.length() * 10;                         // pretend thumbnail size in KB
    }

    public static void main(String[] args) throws Exception {
        String[] files = {"a.jpg", "beach.png", "cat.gif", "dog.jpg", "e.png", "forest.jpg", "g.bmp", "home.png"};
        long start = System.nanoTime();
        List<Future<Integer>> sizes = new ArrayList<>();
        try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
            for (String f : files) sizes.add(pool.submit(() -> makeThumbnail(f)));
        }
        int total = 0;
        for (int i = 0; i < files.length; i++) {
            int kb = sizes.get(i).get();
            total += kb;
            System.out.printf("%-11s %3d KB%n", files[i], kb);
        }
        long ms = (System.nanoTime() - start) / 1_000_000;
        System.out.println("total " + total + " KB, faster than sequential (400 ms): " + (ms < 350));
    }
}

Output Verified by compiling and running

a.jpg        50 KB
beach.png    90 KB
cat.gif      70 KB
dog.jpg      70 KB
e.png        50 KB
forest.jpg  100 KB
g.bmp        50 KB
home.png     80 KB
total 560 KB, faster than sequential (400 ms): true

Eight 50 ms tasks on four threads take about 100 ms instead of 400 ms; reading Futures in order keeps the output stable.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links