I am getting ArrayIndexOutOfBoundException while checking thread safety of ArrayList. We are getting exception.We are getting exception after that we are getting the output but while using vector we are getting proper size. While I am using ArrayList I am getting the below exception:
Exception in thread "Thread-0" java.lang.ArrayIndexOutOfBoundsException: 1851 at java.util.ArrayList.add(ArrayList.java:465) at VectorTut.lambda$0(VectorTut.java:27) at java.lang.Thread.run(Thread.java:750) Size of the list: 1919
After that I get the size of the list.
But when I am providing Vector instead of ArrayList I am getting the proper output. So, my question is how to resolve the exception? Is there anyway to avoid the exception or this is its natural way. Kindly please reply.
import java.util.ArrayList; import java.util.LinkedList; import java.util.Vector; public class VectorTut { public static void main(String[] args) { // Vector<Integer> vector = new Vector<>(5,4); // vector.add(1); // vector.add(2); // vector.add(3); // vector.add(4); // vector.add(5); // System.out.println(vector.capacity()); // vector.add(6); // System.out.println(vector.capacity()); // LinkedList<Integer> linkedList = new LinkedList<>(); // linkedList.add(1); // linkedList.add(2); // linkedList.add(3); // Vector<Integer> vector2 = new Vector<>(linkedList); // System.out.println(vector2); ArrayList<Integer> arrayList = new ArrayList<>(); Thread t1 = new Thread(()->{ for(int i=0;i<1000;i++){ arrayList.add(i); } }); Thread t2 = new Thread(()->{ for(int i=0;i<1000;i++){ arrayList.add(i); } }); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Size of the list: "+arrayList.size()); } }````
Vector
is synchronized."Collections.synchronizedList
as suggested by above mentioned javadoc, at least to confirm if synchronization is the problem )ArrayList
from different threads. There is no way to suggest an alternative for a piece of code whose only purpose is to do the wrong thing. If you had an actual goal, we could suggest ways to achieve the goal.