Three ways to replace ArrayList in Java concurrency to ensure thread safety

1. Use the Vector class released by JDK1.0, because the underlying method uses the synchronized keyword, which is inefficient and is not recommended.

  List<String> list=new Vector<>();

Second, use the synchronizedList() method of the collection class's top-level parent class Collections class, and the incoming parameter is an ordinary Arraylist.

List<String> list=new ArrayList<>();
List<String> list2=Collections.synchronizedList(list);

3. CopyOnWriteArrayList method under JUC, the bottom layer adopts copy-on-write (recommended, higher performance than Vector)

List<String> list=new CopyOnWriteArrayList<>();

 

Guess you like

Origin blog.csdn.net/Zhongtongyi/article/details/108875684