CopyOnWriteArrayList concurrent container,
CopyOnWriteArrayList concurrent container
Copy-On-Write (COW) is an optimization strategy used in program design. The basic idea is that from the very beginning everyone is sharing the same content. When someone wants to modify this content, they will actually Copy the content to form a new content and then modify it, this is a lazy latency strategy. Java concurrency packages starting from JDK1.5 provide two concurrent containers implemented using the CopyOnWrite mechanism. They are CopyOnWriteArrayList and CopyOnWriteArraySet. The CopyOnWrite container is very useful and can be used in many concurrent scenarios.
What is a CopyOnWrite container?
The CopyOnWrite container is the container copied during writing. The general understanding is that when we add elements to a container, instead of directly adding elements to the current container, we first Copy the current container and Copy a new container, add elements to the new container. After adding the elements, point the reference of the original container to the new container. The advantage of doing so is that we can concurrently read the CopyOnWrite container without locking, because the current container does not add any elements. Therefore, the CopyOnWrite container is also an idea of read/write separation. The read and write containers are different.
Implementation principle of CopyOnWriteArrayList
Before using CopyOnWriteArrayList, read its source code to learn how it is implemented. The following code is an implementation of the add method in the CopyOnWriteArrayList (adding an element to the CopyOnWriteArrayList). You can find that the lock is required when adding the object, otherwise, N copies will be copied during multi-thread writing.
public boolean add(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; Object[] newElements = Arrays.copyOf(elements, len + 1); newElements[len] = e; setArray(newElements); return true; } finally { lock.unlock(); } }
No lock is required during read. If multiple threads are adding data to the CopyOnWriteArrayList during read, The read will still read the old data because the old CopyOnWriteArrayList will not be locked during write.
Public E get (int index ){
Return get (getArray (), index );
}
The JDK does not provide CopyOnWriteMap. We can refer to CopyOnWriteArrayList to implement one. The basic code is as follows:
import java.util.Collection;import java.util.Map;import java.util.Set; public class CopyOnWriteMap<K, V> implements Map<K, V>, Cloneable { private volatile Map<K, V> internalMap; public CopyOnWriteMap() { internalMap = new HashMap<K, V>(); } public V put(K key, V value) { synchronized (this) { Map<K, V> newMap = new HashMap<K, V>(internalMap); V val = newMap.put(key, value); internalMap = newMap; return val; } } public V get(Object key) { return internalMap.get(key); } public void putAll(Map<? extends K, ? extends V> newData) { synchronized (this) { Map<K, V> newMap = new HashMap<K, V>(internalMap); newMap.putAll(newData); internalMap = newMap; } }}
The implementation is very simple. As long as we understand the CopyOnWrite mechanism, we can implement various CopyOnWrite containers and use them in different application scenarios.
CopyOnWrite application scenarios
The CopyOnWrite concurrent container is used in the concurrent scenario of reading, writing, and less. For example, in scenarios such as whitelist, blacklist, and product category access and update, if we have a search website in which users enter keywords in the search box, however, some keywords cannot be searched. These keywords that cannot be searched will be put in a blacklist, which is updated every night. When you search, the system checks that the current keyword is not in the blacklist. If so, the system prompts that the keyword cannot be searched. The implementation code is as follows:
Package com. ifeve. book; import java. util. map; import com. ifeve. book. forkjoin. copyOnWriteMap;/*** blacklist service ** @ author fangtengfei **/public class BlackListServiceImpl {private static CopyOnWriteMap <String, Boolean> blackListMap = new CopyOnWriteMap <String, boolean> (1000); public static boolean isBlackList (String id) {return blackListMap. get (id) = null? False: true;} public static void addBlackList (String id) {blackListMap. put (id, Boolean. TRUE);}/*** add blacklist in batches ** @ param ids */public static void addBlackList (Map <String, Boolean> ids) {blackListMap. putAll (ids );}}
The code is simple, but you need to pay attention to two things when using CopyOnWriteMap:
1. Reduce resizing overhead. Initialize the CopyOnWriteMap size as needed to avoid overhead of CopyOnWriteMap resizing during write.
2. Use batch add. Because containers are copied each time they are added, reducing the number of added operations can reduce the number of container copies. For example, use the addBlackList method in the above Code.
Disadvantages of CopyOnWrite
The CopyOnWrite container has many advantages, but there are also two problems, that is, the memory usage and data consistency problems. So pay attention to it during development.
Memory usage problems. Because of the CopyOnWrite write replication mechanism, when performing write operations, the memory will contain both the memory of the two objects, the old object and the newly written object (note: during replication, only the reference in the container is copied, but a new object will be created and added to the new container during writing, while the objects in the old container are still in use, so there are two copies of the object memory ). If these objects occupy a large amount of memory, for example, about 300 MB, then MB of data will be written in, and the memory will occupy MB, in this case, frequent Yong GC and Full GC may occur. Previously, we used a service in our system because the CopyOnWrite mechanism was used every night to update large objects, resulting in a Full GC every night for 15 seconds, and the application response time also increased.
For memory usage problems, you can reduce the memory consumption of large objects by compressing the elements in the container. For example, if the elements are all decimal numbers, you can consider compressing it into a 36-or 64-digit format. Or use other concurrent containers, such as ConcurrentHashMap, instead of using the CopyOnWrite container.
Data Consistency issues. The CopyOnWrite container can only ensure the final consistency of data, but cannot guarantee the real-time consistency of data. Therefore, if you want to read the data you want to write, do not use the CopyOnWrite container.