| preferred AP College board partner for AP classes
AP Computer Science A/Unit 6: Array
Start Practice TestPractice Test
About Exam
hard Solved by 5 students
Java Thread Race Condition
< Prev
Next >

Consider the following code. After the main method executes, the final values in the counts array are not guaranteed to be 2000 for each element. Which statement best explains why the expected values might not be achieved?

public class AtomicMistake {
    private int[] counts = new int[2];
    
    public void incrementBoth() {
        counts[0]++;
        counts[1]++;
    }
    
    public static void main(String[] args) {
        AtomicMistake am = new AtomicMistake();
        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                am.incrementBoth();
            }
        };
        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);
        t1.start();
        t2.start();
    }
}
A

The increments on counts[0] and counts[1] are not atomic, leading to race conditions where some increments may be lost.

B

The array is too small to support two separate threads modifying its values concurrently.

C

The issue is solely due to the multiplication of thread contexts, not the atomicity of operations.

D

The Java memory model automatically ensures atomicity for simple arithmetic on array elements.

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

Question Leaderboard

Rank
User
Correct Count
Attempt Count
Time
Score
#1tykenjcruz11 0m 00s 100
#2bommasam00035 4m 39s 1
#3lightingstrikes134201 0m 00s -10
#4geethasailaja11 4m 52s -192
#5y.seong202712 158h 43m -571,342
Items per page:
10
1 – 5 of 5
No comments yet. Be the first to comment!

AI Tutor

How can I help?

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