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

Java Thread Synchronization and Race Conditions

Mark
< Prev
Next >

Consider the following SharedResource class. What is a potential issue that may arise during the execution of the main method?

public class SharedResource {
    private final int[] data = new int[10];

    public synchronized void modifyData() {
        for (int i = 0; i < data.length; i++) {
            data[i] = data[i] + 1;
        }
    }
    
      public void printData() {
        for (int i = 0; i < data.length; i++) {
            System.out.print(data[i] + " ");
        }
    }
    
    public static void main(String[] args) {
        SharedResource sr = new SharedResource();
        Thread t1 = new Thread(() -> sr.modifyData());
        Thread t2 = new Thread(() -> sr.modifyData());
        t1.start();
        t2.start();
        sr.printData();
    }
}
A

The data array is final, which means it is immune to concurrent modification issues.

B

The threads will never run concurrently due to synchronized methods, so the program is completely thread safe.

C

The modifyData method is synchronized, guaranteeing that no race conditions occur during array modifications.

D

The printData method is unsynchronized, so it may read the array while it is being modified by the other threads.

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|