Go: "Java concurrent Programming" eight: Secure use of collection APIs (with code) in multithreaded environments

Source: Internet
Author: User

Reprint Please specify source:http://blog.csdn.net/ns_code/article/details/17200509


in the collection API, the originally designed vectors and Hashtable are multithreaded secure. For example, for vectors, the methods used to add and delete elements are synchronized. If only one thread interacts with an instance of a vector, it is wasteful to ask for and release object locks, and it is possible to create deadlocks if misuse is synchronized unnecessarily. Therefore, none of the methods for changing the contents of a collection are synchronized. Collections are inherently non-multithreaded security, and when multiple threads interact with the collection, additional measures must be taken to make multithreading secure.

There are several static methods in the collections class that can obtain a collection that is encapsulated by a synchronous method to encapsulate a non-synchronous collection:

public static Collection synchronizedcollention (Collection c)

public static list synchronizedlist (list L)

public static map Synchronizedmap (map m)

public static set Synchronizedset (set S)

public static SortedMap Synchronizedsortedmap (SortedMap sm)

public static SortedSet Synchronizedsortedset (SortedSet ss)

These methods basically return a new class with a synchronous collection method version. For example, to create a list that is multithreaded and secure and supported by ArrayList, you can use the following code:

List List = Collection.synchronizedlist (new ArrayList ());

Note that the ArrayList instance is immediately encapsulated and there is no direct reference to the unsynchronized ArrayList (that is, to encapsulate the anonymous instance directly). This is one of the safest ways. If another thread is to refer directly to the ArrayList instance, it can perform a non-synchronous modification.


The following is an example of a safe traversal of a collection element in a multi-threaded thread. We use iterator to scan the elements in list one by one, and in a multithreaded environment, when traversing elements in the current collection, you generally want to prevent other threads from adding or removing elements. Security traversal is implemented as follows:

[Java]View PlainCopy
  1. Import java.util.*;
  2. Public class Safecollectioniteration extends Object {
  3. public static void Main (string[] args) {
  4. //For security purposes, use only one reference to the synchronization list to ensure that all access is controlled
  5. //collection must be synchronized, here is a list
  6. List wordList = collections.synchronizedlist (new ArrayList ());
  7. the Add method in//wordlist is the synchronous method that gets the object lock for the wordlist instance
  8. Wordlist.add ("iterators");
  9. Wordlist.add ("require");
  10. Wordlist.add ("Special");
  11. Wordlist.add ("handling");
  12. //Gets the object lock for the wordlist instance,
  13. ///iteration, blocking other threads from calling add or remove methods to modify elements
  14. synchronized (wordList) {
  15. Iterator iter = Wordlist.iterator ();
  16. While (Iter.hasnext ()) {
  17. string s = (string) iter.next ();
  18. System.out.println ("found string:" + S + ", length=" + s.length ());
  19. }
  20. }
  21. }
  22. }

It is important to note that in the Java language, most of the thread-safe classes are relatively thread-safe, which guarantees thread-safe operation of the object individually, and we do not need additional safeguards when calling, but for some specific sequential calls, It may be necessary to use an additional synchronization method at the caller's side to ensure the correctness of the call. Examples include vectors, HashTable, Collections's Synchronizedxxxx () method wrapper collections, and so on.

Go: Java Concurrency programming Eight: Secure use of the collection API (with code) in a multithreaded environment

Related Article

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.