| preferred AP College board partner for AP classes
AP Computer Science A/Unit 7: ArrayList
Start Practice TestPractice Test
About Exam
hard Solved by 9 students
Thread-Safe ArrayList Compound Operations
< Prev
Next >

What is required to safely execute a compound operation, such as checking if an ArrayList is empty before accessing an element, when the list is shared among multiple threads?

import java.util.ArrayList;

public class CompoundAction {
    static ArrayList<Integer> list = new ArrayList<>();
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            synchronized(list) {
                if (!list.isEmpty()) {
                    list.remove(0);
                }
            }
        });
        Thread t2 = new Thread(() -> {
            synchronized(list) {
                if (!list.isEmpty()) {
                    System.out.println(list.get(0));
                }
            }
        });
        t1.start();
        t2.start();
    }
}
A

Rely on the thread-safety of ArrayList which is inherent by default

B

Declare the ArrayList as volatile

C

Enclose the entire compound operation in a synchronized block on the shared object

D

Synchronize each individual method call separately

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

Question Leaderboard

Rank
User
Correct Count
Attempt Count
Time
Score
#1kaisuki22 0m 00s 200
#2ponneban00001 1m 14s -84
#3y.seong202701 2m 39s -169
Items per page:
10
1 – 3 of 3
No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy