What are the possible problems caused by adding elements to unsynchronized ArrayList's object by multiple threads simultaneously?
You will usually encounter issues when the list is resized to accommodate more elements. Look at the implementation of ArrayList.add()
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true;}
if there is no synchronization, the array's size will change between the call to ensureCapacityInternal
and the actual element insertion. This will eventually cause an ArrayIndexOutOfBoundsException
to be thrown.
Here is the code that produces this behavior
final ExecutorService exec = Executors.newFixedThreadPool(8);final List<Integer> list = new ArrayList<>();for (int i = 0; i < 8; i++) { exec.execute(() -> { Random r = new Random(); while (true) { list.add(r.nextInt()); } });}
By adding element into unsunchronized ArrayList used by multiple thread, you may get null value in place of actual value as you desired.
This happen because of following code of ArrayList class.
public boolean add(E e) { ensureCapacity(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
ArrayList class first check its current capacity and if require then increment its capacity(default capacity is 10 and next increment (10*3)/2) and put default class level value in new space.
Let suppose we are using two thread and both comes at same time to add one element and found that default capacity(10) has been fulled and its time to increment its capacity.At First threadOne comes and increment the size of ArrayList with default value using ensureCapacity method(10+(10*3/2)) and put its element at next index(size=10+1=11) and now new size is 11. Now second thread comes and increment the size of same ArrayList with default value using ensureCapacity method(10+(10*3/2)) again and put its element at next index (size=11+1=12) and now new size is 12. In this case you will get null at index 10 which is the default value.
Here is the same code for above.
package com;import java.util.ArrayList;import java.util.List;public class Test implements Runnable { static List<Integer> ls = new ArrayList<Integer>(); public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new Test()); Thread t2 = new Thread(new Test()); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(ls.size()); for (int i = 0; i < ls.size(); ++i) { System.out.println(i + " " + ls.get(i)); } } @Override public void run() { try { for (int i = 0; i < 20; ++i) { ls.add(i); Thread.sleep(2); } } catch (Exception e) { e.printStackTrace(); } }}
output:
390 01 02 13 14 25 26 37 38 49 410 null11 512 613 614 715 716 817 918 919 1020 1021 1122 1123 1224 1225 1326 1327 1428 1429 1530 1531 1632 1633 1734 1735 1836 1837 1938 19
After running two or three time you will get null value sometime at index 10 and some time at 16.
As mentioned in above Answer by noscreenname you may get ArrayIndexOutOfBoundsException from this code code. If you remove Thread.sleep(2) it will generate frequently.
Please check total size of array which is less then as you required. According to code it should 40(20*2) but you will get different on every time.
Note : It is possible you may have to run this code multiple time to generate one or multiple scenario.
Here is a simple example: I add 1000 items to a list from 10 threads. You would expect to have 10,000 items at the end but you probably won't. And if you run it several times you will probably get a different result each time.
If you want a ConcurrentModificationException, you can add a for (Integer i : list) { }
after the loop that creates the tasks.
public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newFixedThreadPool(10); List<Integer> list = new ArrayList<> (); for (int i = 0; i < 10; i++) { executor.submit(new ListAdder(list, 1000)); } executor.shutdown(); executor.awaitTermination(1, TimeUnit.SECONDS); System.out.println(list.size());}private static class ListAdder implements Runnable { private final List<Integer> list; private final int iterations; public ListAdder(List<Integer> list, int iterations) { this.list = list; this.iterations = iterations; } @Override public void run() { for (int i = 0; i < iterations; i++) { list.add(0); } }}