"Java Concurrency Programming" Eight: Secure use of collection APIs (with code) in multithreaded environments

Source: Internet
Author: User

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.   
  3. public   class  safecollectioniteration  extends  object {  
  4.      public   static   void  main (String[] args)  {  
  5.         //for security purposes, only one reference to the synchronization list is used, which ensures that all access to the   
  6.         //collection must be synchronized, here is a list   
  7.         list wordlist =  Collections.synchronizedlist (new  arraylist ());   
  8.   
  9.         //wordlist is a synchronous method that gets the object lock of the Wordlist instance   
  10.         wordlist.add (" iterators "
  11.         wordlist.add (" require "
  12.         wordlist.add (" special "
  13.         wordlist.add (" handling "
  14.   
  15.         //gets the object lock of the Wordlist instance,   
  16.         //iterations, blocks other threads from calling add or remove methods to modify the element   
  17.         synchronized   ( wordList )  {  
  18.             iterator  iter = wordlist.iterator ();   
  19.             while   ( iter.hasnext ()  )  {  
  20.                  String s =  (String)  iter.next ();   
  21.                  system.out.println (" found string:  "  + S +  ",  length= "  + s.length ());   
  22. }
  23. }
  24. }
  25. }

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.


"Java Concurrency Programming" Eight: Secure use of collection APIs (with code) in multithreaded environments

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.