Thread Safety test for ArrayList

Source: Internet
Author: User

PublicClassTestthread Implements runnable{PrivateList list; Countdownlatch cdl;PublicTestthread (List List,countdownlatch Cdl) {this.list=ListThis.cdl=Cdl }/** * @see Java.lang.runnable#run ()*/@OverridePublicvoidRun () {Forint i=0;i<500;i++) {list.add ("A"); }Try{cdl.countdown ();}Catch(Exception E) {e.printstacktrace ();} }PublicStaticvoidMain (string[] Args) throws exception{int count=32; Countdownlatch cdl=New Countdownlatch (count); List list=new ArrayList (); //list list=collections.synchronizedlist (new ArrayList ()); Testthread t1=new testthread (list,cdl); for (int i=0;i<count;i++" {new Thread (t1). start ();} cdl.await (); System. out.println ( "size: "+list.size ()); } } 

The conclusion is that when using arraylist, the following error occurs:

"Thread-1452 at java.util.ArrayList.add (arraylist.java:    

After you change to list list=collections.synchronizedlist (new ArrayList ()), It is normal.

list<map<string,object>> data=new arraylist<map<string,object>> ();

So to solve this thread-safety problem you can use collections.synchronizedlist () such as:

list<map<string,object>> data=collections.synchronizedlist (new arraylist<map<string,object> > ());

The other has not changed, the use of the method is almost the same as arraylist, we can refer to the API documentation;

Additional ArrayList and linkedlist; both are an implementation under the interface list, using the same, but with a bit different place, ArrayList suitable for the use of a large number of random access, linkedlist suitable for inserting in the table, delete, both are non-thread-safe, the same workaround (in order to avoid thread safety, the above method, especially the second, is actually very lossy performance).

Thread-safe and non- thread-safe

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 face 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? This is a series of problems, the 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 adds 100 elements, and so on after all the threads are executed, this ArrayList

What should be the size? It's supposed to be 100,000?

PublicClassMain {PublicStaticvoidMain (string[] Args) {//Test 10 timesForint i =0; I <10; i++) {test ();}}PublicStaticvoidTest () {//List list<object> for testing list =New arraylist<object>();//Number of Threads (1000)int threadcount =1000;//Used to allow the main thread to wait for the ThreadCount child thread to execute countdownlatch countdownlatch =NewCountdownlatch (threadcount);//Start ThreadCount Child ThreadsForint i =0; I < threadcount; i++) {thread thread =New Thread (NewMyThread (list,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 size System of the List.Out. println (list.size ()); } }ClassMyThread implements Runnable {Private list<object>ListPrivateCountdownlatch countdownlatch;Public MyThread (list<object> list, countdownlatch Countdownlatch) {this.list = list; this.countdownlatch = countdownlatch;} public void run () {// Each thread adds 100 elements to a list for ( int i = 0; i < 100; i++< Span style= "color: #000000") {list.add (new// complete a child thread  Countdownlatch.countdown (); }} 

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

1 list<object> List = new Arraylist<object> ();

Change into

1 list<object> List = new Vector<object> ();

Run the program Again.

Output result:

100000

100000

Thread Safety test for ArrayList

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.