Java thread-safe and non-thread-safe

Source: Internet
Author: User

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

What is thread safety? What is the difference between thread-safe and non-threading security? Under what circumstances are they used?

Non-thread-safe refers to a problem that can occur with multithreaded operations on the same object . Thread safety is not a problem with multithreaded operations on the same object.
Thread safety must use many synchronized keywords to synchronize control, so it inevitably leads to degraded performance.
So when using, if multiple threads are working on the same object, use a thread-safe vector, or use a more efficient ArrayList.

Non-thread safe! = is not secure
Someone in the process of using an incorrect point of view: My program is multi-threaded, can not use ArrayList to use the vector, so it is safe.
Non-thread-safe is not available in multithreaded environments. Notice what I've said above: multithreading operates on the same object. Note that it is the same object. The top one, for example, is a ArrayList of new in the main thread, and then multiple threads manipulate the same ArrayList object.
If it is a new ArrayList in each thread, and this ArrayList is only used in this thread, then it is certainly not a problem.

Thread-Safe implementation
thread safety is implemented through thread synchronization control , which is the Synchronized keyword.
Here, I use code to implement a non-thread-safe counter and thread-safe counter counter, respectively, and they are multithreaded test.

Public synchronized void Addcount () {count++;}}

Java 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.