Thread-safe and non-thread-safe

Source: Internet
Author: User

What is the difference between ArrayList and vectors? What's the difference between HashMap and Hashtable? What's the difference between StringBuilder and StringBuffer? These are the basic questions that are common in the Java interview. In the face of this problem, the answer is: ArrayList is non-thread-safe, vector is thread-safe, HashMap is non-thread-safe, Hashtable is thread-safe, StringBuilder is non-thread-safe, StringBuffer is thread-safe. These are frequently asked questions during an interview, but in some cases the interviewer will ask: what is thread safety and what is non-thread insecure? Time to use?

For example, create 1000 threads in a main method to add elements to the same list, add 100 elements per thread, and normally the list should be 10W in length when the program is finished. If the implementation class of List is ArrayList (non-thread-safe), then the length of the list after the execution of the program is not fixed! It may be 10W, but it may not be 10W, and arrayindexoutofboundsexception exceptions may occur. But if the list of the implementation class is a vector will not produce this situation, the result must be 10W, this is the difference between the two;

Interpretation:

That is, non-thread-safe refers to a problem that can occur when multiple threads operate on the same object, while thread safety is not a problem;

However, thread safety is used to synchronized to control thread synchronization, so the corresponding performance of thread safety is relatively low;

It is not a problem to use a non-thread-safe implementation class when not multiple threads are accessing the same object.

At the time of use, both can be used as long as there are not multiple threads accessing the same object

Thread-safe and non-thread-safe

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.