Java notes copyonwritearraylist

Source: Internet
Author: User

Before writingCodeEncountered a concurrentmodificationexception. Baidu found that it was caused by the use of iterator to change the original data.

The business requirements are as follows:

There is a data listener list. When the system receives the data, it traverses each item in the list and sends the data. The listener can be added or deleted during traversal.

In this case, you can use copyonwritearraylist to implement the listener list.

The principle is as follows:

Moving a reference from an object to another object in Java does not require CPU time. It can be considered as an atomic operation.

In Java, if an object still has a reference, it will not be recycled by CG.

Copyonwritearraylist is based on the above two features, when the list has been updated, directly copy the original list, and then update the new list, after that, move the reference to the new list. If the old list is still in use (for example, traversing), it will continue to be valid. In this way, there will be no changes to the objects in use (read and write occur on two objects respectively), and the read operation does not have to wait for the completion of the write operation, this removes the need to use locks to speed up reading.

 

In addition, copyonwritearraylist needs to copy the entire array during writing. Therefore, this operation is time-consuming and is not suitable for businesses with frequent writing.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.