Java: What is thread security?

Source: Internet
Author: User


 


What is thread security?If multiple threads are running simultaneously in the process where your code is located, these threads may run the code at the same time. If the result of each running is the same as that of a single thread, and the value of other variables is the same as expected, it is thread-safe.


ExampleFor example, an ArrayList class may take two steps to add an element: 1. Store this element at the Items [Size] position; 2. Increase the Size value.

When a single thread is running, if the Size is 0, after an element is added, the element is in the position 0 and the Size is 1;
In the case of multithreading, for example, if there are two threads, thread A first stores the elements in the position 0. However, at this time, the CPU scheduling thread A is paused, and thread B gets the chance to run. Thread B also adds an element to this ArrayList, because the Size is still equal to 0 (note that we assume that two steps are required to add an element, thread A only completes step 1), so thread B also stores the elements in the position 0. Then, both Thread A and thread B continue to run, increasing the Size value.
Well, now let's take a look at the ArrayList. There is actually only one element, which is stored in the position 0, but the Size is equal to 2. This is "thread unsafe.
 

<

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.