Are you taking CLEP classes? Try clep.ai
| 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

Mark
< Prev
Next >

Consider the following Java code snippet. Which statement best describes a potential concurrency-related problem that could occur when this code is executed?

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

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

B

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

C

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

D

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

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.

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy|