| preferred AP College board partner for AP classes
AP Computer Science A/Unit 7: ArrayList
Start Practice TestPractice Test
About Exam
hard
Java Thread Synchronization and Visibility
< Prev
Next >

In the provided code, a writer thread modifies a shared ArrayList while a reader thread accesses it. Which approach best ensures that the reader thread will observe the most recent list size?

import java.util.ArrayList;

public class VisibilityTest {
    static ArrayList<Integer> list = new ArrayList<>();
    public static void main(String[] args) throws InterruptedException {
        Thread writer = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                list.add(i);
                try { Thread.sleep(20); } catch (InterruptedException e) {}
            }
        });
        Thread reader = new Thread(() -> {
            try { Thread.sleep(50); } catch (InterruptedException e) {}
            System.out.println(list.size());
        });
        writer.start();
        reader.start();
        writer.join();
        reader.join();
    }
}
A

Encapsulate both the write and read operations within a synchronized block on the shared list

B

Replace ArrayList with LinkedList

C

Insert Thread.sleep calls between operations to ensure memory consistency

D

Declare the ArrayList as volatile

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