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

In the context of concurrent execution, why might the counts array not reflect the expected values after both threads execute?

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 issue is solely due to the multiplication of thread contexts, not the atomicity of operations.

C

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

D

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

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

Question Leaderboard

Rank
User
Correct Count
Attempt Count
Time
Score
#1tykenjcruz11 0m 00s 100
#2lightingstrikes134201 0m 00s -10
#3bommasam00024 4m 15s -75
#4geethasailaja11 4m 52s -192
#5y.seong202712 158h 43m -571,342
APFIVE © 2020.
Email: [email protected]|Privacy Policy