THINK FIRST·CODE LATER

← All labs

Threads in practice: a parallel sum with a thread pool

Problem

Use real Java threads to sum a large array in parallel — the way an EdgeCampus analytics server splits work across cores.

Input: first line n t (number of values, number of worker tasks), then n integers (each fits in an int; the total fits in a long).

Split the array into t contiguous chunks as evenly as possible: chunk sizes differ by at most one, and the first n % t chunks get one extra element. Submit one task per chunk to an ExecutorService with a fixed pool of min(t, 4) threads, and collect the results with Future.get() in chunk order.

Print one line per chunk: chunk k [from..to]: sum (indices inclusive, 0-based; a chunk may be empty: then print chunk k [empty]: 0), then Total: T and Check: OK if T equals a sequential sum, otherwise Check: MISMATCH.

Input:

10 3
1 2 3 4 5 6 7 8 9 10

Output:

chunk 0 [0..3]: 10
chunk 1 [4..6]: 18
chunk 2 [7..9]: 27
Total: 55
Check: OK

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

os3-4-data-1.txt

10 3
1 2 3 4 5 6 7 8 9 10
What your program must print for os3-4-data-1.txt
chunk 0 [0..3]: 10
chunk 1 [4..6]: 18
chunk 2 [7..9]: 27
Total: 55
Check: OK

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < os3-4-data-1.txt

Windows PowerShell does not understand <:

Get-Content os3-4-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.