Multi-thread 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.

At this point, if you continue to ask: what is thread safety? What is the difference between thread-safe and non-threading security? Under what circumstances are they used?

Thread Safety:

  When multiple thread classes concurrently manipulate a method of a class,( within that method ) to modify The value of a member variable of that class, there is no error. Then we say that this method is thread-safe.

The key to whether a method of a certain class is thread safe is:

(1) Whether the method modifies the member variables of the class ;

(2) whether to lock the method ( Whether it is decorated with the synchronized keyword).

Thread is not secure:

  When multiple thread classes concurrently manipulate a method of a class,( within that method ) to modify The value of a member variable of that class, It is easy to make mistakes , so we say that this method is thread insecure. If you want to turn this method into thread-safe, use the synchronized keyword to modify the method.

Note: with the synchronized keyword modification method, will cause lock, although can make the method thread security, but will greatly reduce the execution efficiency of the method, it is prudent to use the keyword.

  

Thread Safety:

Multiple threads ( classes ) A security issue can occur when you execute the same code at the same time.

Look at the following code to understand thread safety

Public Double Pi () {
int a = 22;
int B = 7;
return new Double (A/b);
}

  Now, when executing this method, each thread has its own separate stack area. When a thread enters a method execution, a method variable is created in the method code snippet and the stack area of the threads is saved (the static method is also placed here). When different threads execute this code, there are different A/ b variables. So this is thread-safe because there is no data sharing.

  Consider the following example, which executes only once in multithreaded situations and can reuse the results:

Private Double pi = null;
Public Double Pi () {
if (pi = = null) {
PI = new Double (22/7);
}
return pi;
}

This place has been optimized, but unfortunately he is not thread safe.

  when two threads execute concurrently, they go to the pi==null location, which may Create a new dirty data .

Consider this example which uses ThreadLocal to make the Method pi () again Thread-safe while still offering performance GA Ins:

private static ThreadLocal pi = new ThreadLocal ();
Public Double Pi () {
if (pi.get () = = null) {
Pi.set (New Double (22/7));
}
Return (Double) pi.get ();
}
ThreadLocalclass encapsulates any type of object and binds it to the current thread. Thread ExecutionPi ()method, the instancePireturns the object of the current thread. Such a call is thread-safe.
   Writing Thread-safe Code requires you are careful when using instance variables or static variables, especially when  You is modifying objects that may is used by other threads.  

  with ArrayList or Vector, How do they choose?

Thread safety: Refers to the multithreading operation of a method of the same object, no error occurs when modifying member variables of the class.

Non-thread safe: An error may occur when you modify a member variable for a method of the same object in a multithreaded operation.

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. Note that it says: Multithreading operates on the same object. Note that the same object

For example, the top simulation is a ArrayList of new in the main thread, and then multiple threads manipulate the same ArrayList object . There will be security issues.

 If a new ArrayListis in each thread, and this ArrayList is used only in this thread, then it is certainly not security issues.

Summary:

If multiple threads modify the member variables of an externally transmitted object at the same time, an error can easily occur, which we call thread insecurity. ( This method of this class is thread insecure.) To thread-safe, decorate with the synchronized keyword ).

  

Multi-thread 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.