| preferred AP College board partner for AP classes
AP Computer Science A/Unit 6: Array
Start Practice TestPractice Test
About Exam
hard
Shared Array Modification in Threads
< Prev
Next >

What concurrency-related problem is most likely in this code snippet?

public class ConcurrentSum {
    private int[] numbers = {1, 2, 3, 4, 5};

    public void computeSum() {
        int sum = 0;
        for (int num : numbers) {
            sum += num;
            numbers[0] = 0; // modifying the array during iteration
        }
        System.out.println(sum);
    }
    
    public static void main(String[] args) {
        ConcurrentSum cs = new ConcurrentSum();
        Thread t1 = new Thread(() -> cs.computeSum());
        Thread t2 = new Thread(() -> cs.computeSum());
        t1.start();
        t2.start();
    }
}
A

Assigning to the first element during iteration will certainly raise an ArrayIndexOutOfBoundsException.

B

The computeSum method is thread-safe because the local variable sum is confined to each thread.

C

Enhanced-for loops automatically synchronize access to arrays, so no issue arises.

D

The concurrent modification of the array during iteration can lead to unpredictable behavior or logical errors.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: [email protected]|Privacy Policy