Are you taking CLEP classes? Try clep.ai
| 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

Mark
< 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

Replace ArrayList with LinkedList

B

Declare the ArrayList as volatile

C

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

D

Insert Thread.sleep calls between operations to ensure memory consistency

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|