| preferred AP College board partner for AP classes
Login
 
Register
AP Computer Science A/Unit 7: ArrayList
Start Practice Test
Share
Thread-Safe ArrayList Compound Operations
< Prev
Next >

To safely perform compound operations on a shared ArrayList, what is necessary?

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

Synchronize each individual method call separately

D

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

Check Answer
APFIVE © 2020.
Email: [email protected]|Privacy Policy