ArrayList is a very useful Collection in Java, I guess most used one as well but it is not synchronized. What this mean? It means you cannot share an instance of ArrayList between multiple threads if they are not just reading from it but also writing or updating elements. So
how can we synchronize ArrayList? Well, we'll come to that in a second but did you thought why ArrayList is not synchronized in first place? Since multi-threading is core strength of Java and almost all Java programs has more than one thread, why Java designer not makes it easy for ArrayList to be used in such environment? Answer lies in performance, there is performance cost associated with synchronization and making ArrayList synchronized would have made it slower. So, they definitely thought about it and left ArrayList as non-synchronized to keep it fast, but at the same time they have provided easy ways to make it synchronized and this is what we are going to learn in this tutorial. Collections class has several method to
create synchronized List, Set and Map and we will use
Collections.synchronizedList() method to make our ArrayList synchronized. This method accepts a List which could be any implementation of
List interface e.g.
ArrayList,
LinkedList and returns a synchronized (thread-safe) list backed by the specified list. So you can also use this technique to make LinkedList synchronized and thread-safe in Java.