#478 Parallel Sum of a List

Companies:
Itone
Themes:
JavaConcurrencyPractice

A list of numbers is provided, and the sum of all numbers must be calculated.

The calculation must be fast. Because the list is large, the sum should be calculated as follows: split the input list into parts using the split method (no time needs to be spent implementing it; it is included only to avoid adding a library).

Each sublist must be submitted to a separate thread where its sum is calculated, using 10 threads in total. After all 10 threads finish, collect and add the results to obtain the final sum.

/**
 * Calculate the sum of list elements, more than 1 million elements,
 * using 10 threads.
*/

public static long sum(List<Long> numbers) {
    final int threads = 10;
    List<List<Long>> subLists = split(numbers, threads);


    // TODO: make it work!

    return ???;

}

private static List<List<Long>> split(List<Long> numbers, int parts) {
    int size = numbers.size();
    int subListSize = (int) Math.ceil((double) size / parts);

    List<List<Long>> result = new ArrayList<>(parts);
    for (int i = 0; i < parts; i++) {
        int fromIndex = i * subListSize;
        if (fromIndex >= size) {
            result.add(Collections.emptyList());
        } else {
            int toIndex = Math.min((i + 1) * subListSize, size);
            List<Long> sublist = numbers.subList(fromIndex, toIndex);
            result.add(sublist);
        }
    }
    return result;
}

Question review

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in