Java-Collection Class (ii)

Source: Internet
Author: User

Usage Scenarios1. Multithreading

(1) in the original collection class before jdk1.5, only vector, Stack, hashtable, enumeration, etc. are thread-safe, others are non-thread safe.
Non-thread-safe collections in multithreaded operations, dirty data appears, such as

Final List<string> tickets =NewArraylist<string> (); for(inti =0; I <100000; i++) {Tickets.add ("NO,"+ i); } System. out. println ("Start1 ..."); for(inti =0; I <5; i++) {Thread thread =NewThread () { Public void Run() { while(true) {if(Tickets.size () >0) System. out. println ("Thread:"+thread.currentthread (). GetId () +" "+ Tickets.remove (0));Else                             Break;            }                }            };        Thread.Start (); }

Operation Result:

 ...   ...  thread : 13  no,98687  thread : 12  NO, 96534  thread : 10  no,96534  thread : 10  NO, 98687   ...   ...  thread : 10  null  thread : 12  null   

Thread insecurity causes multiple threads to call remove while manipulating the List to read and write.
ArrayList modified to Stack, problem solved.
(2) thread-safe collections are also subject to the fail-fast detection mechanism, which means that the elements of the collection cannot be modified at iteration time. Once a violation of this rule is found, a Concurrentmodificationexception exception is thrown. To modify elements during an iteration, you need to synchronize the locks for iterations and modifications.
The concurrentmodificationexception exception will appear as shown in the following code.

Final list<string> Tickets = collections. Synchronizedlist (NewArraylist<string> ()); for(inti =0; I < -; i++) {Tickets.add ("NO,"+ i); } System. out. println ("Start1 ..."); for(inti =0; I <5; i++) {Thread thread =NewThread () { Public void Run() { while(true) {if(Tickets.size () >0) System. out. println ("Thread:"+ Thread.CurrentThread (). GetId () +" "+ Tickets.remove (0));Else                             Break;            }                }            };        Thread.Start (); } System. out. println ("Start2 ...");NewThread () { Public void Run() { for(String s:tickets) {System. out. println (s); }}}.start ();

(3) Get a thread-safe collection
1. Use thread-safe collection classes such as vectors, stacks, Hashtable, enumeration, and so on.
2. Use COLLECTIONS.SYNCHRONIZEDXXX to convert a non-thread-safe collection into a thread-safe collection.
3. New thread-Safe collection classes after using jdk1.5, such as Concurrentlinkedqueue, Concurrenthashmap, and so on.

2. Precautions for use

(1) ArrayList, such as sequential storage set suitable for random access, linklist, such as the form of a linked list for inserting delete and iteration operations.
(2) The collection interface inherits the Iterable interface, and each collection supports iterative traversal and foreach functionality except for map.
(3) Weakhashmap support key recovery, improve performance, in the Open source project Android-universal-image-loader with Weakhashmap save need to display ImageView support recycling.
(4) The HASHMAP key is judged by the same criteria as the key equal and hashcode. As follows

Private Static void Testhashmapkey() {System. out. println ("------Test hash Map key start------"); String[] Sampletest = {"Aa","BB","AA"}; Hashmap<stringequal, integer> strhaspmap =NewHashmapNewStringequal (sampletest[0]),NewStringequal (sampletest[1]),NewStringequal (sampletest[2]) };//key Whether the same judgment is equal and hash are the same, AA and BB hash of the sameStrhaspmap.put (strarray[0],0); Strhaspmap.put (strarray[1],1); Strhaspmap.put (strarray[2],2); Set<stringequal>Set= Strhaspmap.keyset (); for(Stringequal str:Set) {System. out. println (Strhaspmap.Get(str)); }    }Private Static classstringequal {PrivateString str; Public stringequal(String str) { This. str = str; } @Override PublicBooleanequals(Object obj) {return true; } @Override Public int hashcode() {returnStr.hashcode (); }    }
------testhashmapkeystart------12

The hashcode algorithm for String is s[0]*31^ (n-1) + s[1]*31^ (n-2) + ... + s[n-1], the hash of "AA" and "BB" is the same, Stringequal class equal default is True, then "AA" and "BB" Determine For the same key.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java-Collection Class (b)

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.