Concurrent Modification of an ArrayList
Consider the following code. When the main method is executed, two threads concurrently modify the myList object. What is the most likely issue to arise from this concurrent access?
import java.util.ArrayList;
import java.util.List;
public class ListUpdater implements Runnable {
private List<Integer> list;
public ListUpdater(List<Integer> list) {
this.list = list;
}
public void run() {
for (int i = 0; i < 1000; i++) {
list.add(i);
}
}
}
public class ListTest {
public static void main(String[] args) throws InterruptedException {
List<Integer> myList = new ArrayList<>();
Thread t1 = new Thread(new ListUpdater(myList));
Thread t2 = new Thread(new ListUpdater(myList));
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(myList.size());
}
}
A
Race condition resulting in data corruption due to the non-thread-safe nature of ArrayList.
B
OutOfMemoryError because ArrayList cannot handle multiple threads.
C
InterruptedException being thrown due to concurrent modifications.
D
Deadlock caused by the inherent locking mechanism in ArrayList.
Question Leaderboard
Not enough data yet to show leaderboard.
