Learning Resources: http://www.cnblogs.com/dolphin0520/p/3938914.html
The Copyonwrite container is the container that is copied when it is written. The popular understanding is that when we add elements to a container, instead of adding them directly to the current container, the current container is copied, a new container is duplicated, the new container is added, the element is added, and the reference to the original container is pointed to the new container. The advantage of this is that we can read the Copyonwrite container concurrently, without having to lock it, because the current container does not add any elements. So the Copyonwrite container is also a reading and writing separation of ideas, reading and writing different containers.
Copyonwrite concurrent containers are used for read-write-less concurrency scenarios. No need to lock when reading
There are two things to note about using Copyonwritemap:
1. Reduce the expansion overhead. According to the actual needs, initialize the size of the copyonwritemap to avoid the overhead of copyonwritemap expansion when writing.
2. Use bulk Add. Because each time it is added, the container replicates every time, so you can reduce the number of times the container replicates by reducing the number of additions.
Disadvantages of Copyonwrite
memory consumption issues . Because of the copyonwrite of the write-time replication mechanism, so when the write operation, memory will be stationed at the same time the memory of two objects, the old object and the newly written object (note: In the copy is copied only the reference in the container, but at the time of writing will create a new object to add to the new container, The object of the old container is still in use, so there are two copies of the object memory. If these objects occupy a large amount of memory, say 200M or so, then write 100M data in, memory will occupy 300M, then this time is likely to cause frequent Yong GC and full GC. Before we used a service in our system because the copyonwrite mechanism is used to update large objects every night, resulting in a full GC of 15 seconds per night, the application response time also becomes longer.
For memory usage, you can reduce the memory consumption of large objects by compressing the elements in the container, for example, if the elements are all 10 binary numbers, consider compressing them into 36 or 64 binary. Or do not use the Copyonwrite container, but use other concurrent containers, such as Concurrenthashmap.
data consistency issues . The Copyonwrite container can only guarantee the final consistency of the data and cannot guarantee the real-time data consistency. So if you want to write the data that can be read right away, please do not use the Copyonwrite container.
Copyonwrite container of Java concurrent container