Concurrent container
Concurrent container overview
ConcurrentHashMap; thread-safe HashMap
CopyOnWriteArrayList: thread-safe List
BlockingQueue: This is an interface that represents a blocking queue, which is very suitable as a data sharing channel.
ConcurrentLinkedQueue: An efficient non-blocking concurrent queue, implemented using a linked list. It can be regarded as a thread-safe LinkedList
ConcurrentSkipListMap: it is a Map that uses the data structure of a jump table for quick search.
History of collections
Vector和Hashtable
Using synchronized, the concurrency performance is poor.
ArrayList和HashMap
Although these two classes are not thread-safe, you can use Collections.synchronizedList(new ArrayListt) and Collections.synchronizedMap(new HashMap<K,V>()) to make them thread-safe.
ConcurrentHashMap
- Introduction to Map
- Why do you need ConcurrentHashMap
- Analysis of HashMap
- Implementation and analysis of ConcurrentHashMap of JDK1.7
- ConcurrentHashMap implementation and source code analysis of JDK1.8
- Regarding the advantages and disadvantages of JDK1.7 and JDK1.8, why change the structure of 1.7 to the structure of 1.8?
- Combined operation: ConcurrentHashMap is also not thread-safe
- Actual production case
Introduction to Map
Common methods of Map interface
/**
* @Classname MapDemo
* @Description 演示Map的基本用法
* @Date 2021/2/26 10:23
* @Created by YoungLiu
*/
public class MapDemo {
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<>();
System.out.println(map.isEmpty());
map.put("123",23);
map.put("456",12);
System.out.println(map.keySet());
System.out.println(map.get("123"));
System.out.println(map.size());
System.out.println(map.containsKey("123"));
}
}
Why is HashMap not thread safe?
- At the same time put collision causes data loss
- At the same time put expansion leads to data loss
- 100% CPU caused by infinite loop
100% CPU caused by infinite loop
When multiple threads operate the hashmap at the same time, it will cause an endless loop of the linked list. You point to me and I point to you.
hashmap analysis
ConcurrentHashMap's putVal process
The get process of ConcurrentHashMap
CopyOnWriteArrayList
Concurrent queue
Why use queues
Use queues to transfer data between threads: producer-consumer model, bank transfer
- Queue
- BlockingQueue
BlockingQueue Blocking Queue
1. What is a blocking queue
2. Introduction of main methods
3. ArrayBlockingQueue
4.LinkedBlockingQueue
5. PriorityBlockingQueue
6. SynchronousQueue