How does ArrayList, LinkedList, and HashMap ensure multi-thread safety

Thread synchronization refers to the coordination of multiple threads, defining how multiple threads access specific resources, and avoiding the problem of data inconsistency caused by concurrent access by multiple threads. ArrayList, LinkkedList, and HashMap are the most commonly used data structures, but they are not thread-safe. In a multi-threaded scenario, if control is not performed, it may cause thread safety issues.

Solve ArrayList, LinkedList thread safety method

1. Inherit Arraylist, and then rewrite or write your own methods as required. These methods should be written as synchronized, and call the ArrayList method in these synchronized methods.

2. Use Collections.synchronizedList(); The method of use is as follows:

假如你创建的代码如下:List<Map<String,Object>> data=new ArrayList<Map<String,Object>>();

那么为了解决这个线程安全问题你可以这么使用Collections.synchronizedList(),如:

List<Map<String,Object>> data=Collections.synchronizedList(new ArrayList<Map<String,Object>>());

Nothing else has changed, and the method used is almost the same as ArrayList. You can refer to the api document;

In addition, let’s talk about ArrayList and LinkedList; these two are both implementations of the interface List. The usage is the same, but the place of use is a little different. ArrayList is suitable for a large number of random accesses, and LinkedList is suitable for use in a table. Use when inserting and deleting, both of which are not thread safe, and the solution is the same as above (in order to avoid thread safety, the above method, especially the second method, is actually very performance-lossing).

Solve the HashMap thread safety method
1. Inherit HashMap, rewrite or write your own methods as required, these methods should be written as synchronized, call the method of HashMap in these synchronized methods
2. Use Collections.synchronizedMap()
3. Use ConcurrentHashMap instead, It is not recommended for new code to use Hashtable. HashTable inherits from Dictionary. Only one thread can write Hashtable at any time. Concurrent performance is not as good as ConcurrentHashMap because ConcurrentHashMap introduces segment locks. Use HashMap for scenarios that do not require thread safety, and use ConcurrentHashMap for scenarios that require thread safety.

Guess you like

Origin blog.csdn.net/u011582840/article/details/107480825