Java Concurrent Programming: implementation of copyonwrite container
Java Concurrent Programming: copyonwritearraylist of concurrent container (Reprint)
Original link:
Copy on write, referred to as cow, is an optimization strategy used in program design. The basic idea is that everyone is sharing the same content from the beginning. When someone wants to modify the content, he will really copy the content to form a new content and then change it. This is a delayed laziness strategy. From jdk1 5 starts Java and provides two concurrent containers implemented using copyonwrite mechanism in the contract. 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 that is copied on write. The popular understanding is that when we add elements to a container, we do not directly add them to the current container, but first copy the current container, copy a new container, then add elements to the new container, and then point the reference of the original container to the new container after adding elements. The advantage of this is that we can read the copyonwrite container concurrently without locking, because the current container will not add any elements. Therefore, the copyonwrite container is also an idea of separating reading and writing. Reading and writing are different containers.
Implementation principle of copyonwritearraylist
Before using copyonwritearraylist, let's read its source code to understand how it is implemented. The following code is the implementation of the add method in copyonwritearraylist (adding elements to copyonwritearraylist). It can be found that locking is required when adding, otherwise N copies will be copied when writing by multiple threads.