Thread safety considerations for the Operations collection--java

Source: Internet
Author: User

Run Scenario: Multiple threads call ArrayList at the same time to store elements

Two threads A and b, when a thread is called, there is no element in the list temporarily, at this time, the size value of the list is 0, and a when adding elements, add an element, the size of the list is still 0, in the [0] location of an element, storage, Our CPU on the A-thread task of the scheduled pause, and then start dispatching B thread, the same B-thread is also the list to do element storage operations, the list size is 0, and the B thread also adds an element to the list, at [1] position, also holds an element, resulting in this time, Our list contains two elements, and after the B thread has finished the add process, not waiting for our CPU to recover the A-thread operation, if there is a C thread to the list to do the query work, then the query to the list of size is 1, and there are two elements contained in it-- This means that the ArrayList thread is not secure,

Similarly, if it happens in HashSet, the problem also exists.

Thread safety considerations for the Operations collection--java

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.