Thread-safe and Non-thread-safe in Java

Source: Internet
Author: User

Original: http://blog.csdn.net/xiao__gui/article/details/8934832

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. Because this is last night on the back of the "java plane test book" Above. 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? Such a series of problems, a mouthful of old blood is sprayed out ...

Non-thread-safe Phenomenon Simulation

This is illustrated by using both ArrayList and Vectors.

The following code, in the main thread, new a non-thread-safe arraylist, and then open 1000 threads to add elements to this arraylist, each thread to add 100 elements, and so on when all the threads execute, the size of this ArrayList should be how much? It's supposed to be 100,000?

PublicClassmain{Publicstatic void main (string[] Args) {Test 10 timesfor (int i =0; I <10; I++) {test ();}}Publicstatic void Test () {List to test withList<object>List =New Arraylist<object> ();Number of threads (threadcount) int =1000;Used to allow the main thread to wait for the ThreadCount child thread to execute countdownlatch countdownlatch =New Countdownlatch (threadcount);Start ThreadCount Child Threadsfor (int i =0; I < threadcount; I++) {thread thread =New Thread (New MyThread (list, countdownlatch)); Thread.Start (); }try {The main thread waits for all child threads to complete, and then executes the countdownlatch.await () down. }Catch (interruptedexception e) {e.printstacktrace ();}List of size System.out.println (List.size ()); }}ClassMyThreadImplementsrunnable{private List<Object > list; private countdownlatch countdownlatch; public MyThread (list<object> list, countdownlatch countdownlatch) {this. list = list; this.countdownlatch = countDownLatch;} public void run () {//each thread adds 100 elements to the list for ( int i = 0; i < 100; i++) {list.add ( Span class= "hljs-keyword" >new Object ()); } //complete A child thread Countdownlatch.countdown ();}}        
      1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • Ten
    • one
    • 2
    • (
    • )
    • +
    • +
    • /
    • 0
    • +
    • all
    • +
    • +
    • +
    • -
    • 29
    • +
    • +
    • all
    • +
    • +
    • PNS
    • up
    • i>39
    • 48
    • all
    • /
    • /
    • /
    • /li>
    • ,
    • ,
    • ,
    • up-
    • -
    • +
    • -
    • +
    • *
    • +
    • ,
    • ,
    • +
    • $
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68

There were 10 tests on it (why test 10 times?). Because non-threading security does not always cause problems).
Output result:

99946

100000

100000

100000

99998

99959

100000

99975

100000

99996

The above output found that not every test results are 100000, several times the final ArrayList size is less than 100000, even occasionally throws a indexoutofboundsexception Exception. (if you don't have this phenomenon you can try it a few more times)
This is the problem with non-threading Security. If the above code is used in a production environment, there will be a Bug.

And then using a thread-safe vector to test it, the above code changes one place, in the test () method
List<Object> list = new ArrayList<Object>();
Switch
List<Object> list = new Vector<Object>();

Run the program Again.

Output result:

100000

100000

100000

100000

100000

100000

100000

100000

100000

100000

Run a few more times and find it all 100000, without any problems. Because vectors are thread-safe, there is no problem when working with the same vector object in multithreaded Operation.

If you try again with linkedlist, there will also be ArrayList similar problems, because LinkedList is also non-thread Safe.

How to choose between them

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.

Non-thread-safe counters:

PublicClass main{PublicStaticvoidMain (string[] Args) {Test 10 timesForint i =0; I <10; I++) {test ();}}PublicStaticvoidTest () {Counter Counter Counter =New Counter ();Number of Threads (1000)int threadcount =1000;Used to allow the main thread to wait for the ThreadCount child thread to execute countdownlatch countdownlatch =New Countdownlatch (threadcount);Start ThreadCount Child ThreadsForint i =0; I < threadcount; I++) {thread thread =New Thread (New MyThread (counter, countdownlatch)); Thread.Start (); }try {The main thread waits for all child threads to complete before executing the Countdownlatch.Await (); }Catch (interruptedexception e) {e.printstacktrace ();}The value of the counter System.Out.println (counter.getcount ()); }}class MyThread implements runnable{Private Counter Counter;Private Countdownlatch countdownlatch;PublicMyThread (Counter Counter, countdownlatch Countdownlatch) {This.counter = counter;This.countdownlatch = countdownlatch;} public void run () { //per thread to counter 10,000 cumulative for (int i = 0; i < 10000; I++) {counter . Addcount (); } //completion of a child thread Countdownlatch.countdown ();}} Class counter{ Private int count = 0; public int getcount () { return count;} public  void addcount () {count++;}}            
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21st
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21st
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83

In the above test code, 1000 threads are turned on, each thread increments the counter 10,000 times, and the final output should be 10000000.

however, the counter in the above code is not synchronized, so it is not thread-safe.

Output result:

9963727

9973178

9999577

9987650

9988734

9988665

9987820

9990847

9992305

9972233

Change the counter to a thread-safe counter with a slight modification:

class Counter{    private int count = 0;    public int getCount() { return count; } public synchronized void addCount() { count++; }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

The above just adds the synchronized synchronization control to the Addcount () method and becomes a thread-safe counter. Execute the program Again.

Output result:

10000000

10000000

10000000

10000000

10000000

10000000

10000000

10000000

10000000

10000000

Thread-safe and Non-thread-safe in 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.