| preferred AP College board partner for AP classes
AP Computer Science A/Unit 6: Array
Start Practice TestPractice Test
About Exam
hard Solved by 1 students
Volatile Keyword and Array Thread Safety
< Prev
Next >

Despite using the volatile keyword for the array reference, what potential issue remains in the code?

public class VolatileArray {
    private volatile int[] data = {0, 0, 0, 0};
    
    public void updateElement(int index, int value) {
        data[index] = value;
    }
    
    public static void main(String[] args) {
        VolatileArray va = new VolatileArray();
        Runnable r = () -> {
            for (int i = 0; i < va.data.length; i++) {
                va.updateElement(i, i + 1);
            }
        };
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.start();
        t2.start();
    }
}
A

The volatile keyword prevents the array from being modified by multiple threads completely.

B

The volatile keyword here ensures perfect thread safety for the updateElement method and its array elements.

C

Using volatile on an array makes all its elements immutable, eliminating any risk of mutation.

D

The volatile keyword does not provide atomicity or visibility guarantees for individual array elements, so race conditions can still occur.

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