Java Multithreading (10) using a thread-safe collection

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/xingjiarong/article/details/48046751

In multi-threading, if you want to modify a data structure concurrently, you are likely to break the structure. For example, a thread might want to insert an element into a hash table, if it is stripped of control when it adjusts the link relationship between buckets, and there is another thread that is traversing the linked list, an exception or a dead loop can occur.

A shared data structure can be secured through locks, but it may be easier to choose a thread-safe implementation as an alternative.

one, the old thread-safe collection

Any collection class can become thread-safe by using the synchronization wrapper:

List<E> synchArrayList = Collections.synchronizedList(new ArrayList<E>());Map<K,V> synchMap = Collections.synchronizedList(new HasMap<K,V>());

The method of the result collection is protected with a lock, providing thread-safe access.

If you want to iterate over the collection when another thread is likely to make modifications, you need to use a blockade.

synchronized(synchHashMap){    Iterator<K> iter = synchHashMap.keySet().iterator();    while(iter.hasNext())        //遍历}

If you use the For Each loop, you must use the same code because the iterator is used by the loop. If another thread modifies the collection during the iteration, the iterator is invalidated and the concurrentmodificationexception exception is thrown, so that concurrent modifications can be reliably detected.

ii. efficient images, collections, and queues

The Java.util.concurrent package provides an efficient implementation of images, ordered sets, and queues: Concurrenthashmap, Concurrentskiplistmap, Concurrentlinkedqueue. These collections minimize competition by allowing concurrent access to different parts of the data structure through complex algorithms.

These collections return iterators with weak consistency. This means that iterators do not necessarily reflect all of the modifications they have been constructed, but they do not return the same value two times, and do not throw concurrentmodificationexception exceptions.

For example, the following example:

Importjava.util.*;Importjava.util.concurrent.*;/ * * Concurrentlinkedqueue is a "thread-safe" queue, and LinkedList is non-thread-safe. * * Below is an example of "multiple threads working simultaneously and traversing the queue" * (01) The program works correctly when the queue is a Concurrentlinkedqueue object. * (02) When the queue is a LinkedList object, the program generates an Concurrentmodificationexception exception. * * @author Skywang * * Public  class Main {    //Todo:queue is an LinkedList object, the program will make an error.     //private static queue<string> Queue = new linkedlist<string> ();    Private Staticqueue<string> queue =NewConcurrentlinkedqueue<string> (); Public Static void Main(string[] args) {//Start two threads at a time to operate the queue!         NewMyThread ("Ta"). Start ();NewMyThread ("TB"). Start (); }Private Static void Printall() {String value; Iterator iter = Queue.iterator (); while(Iter.hasnext ())            {value = (String) iter.next (); System.out.print (value+", ");    } System.out.println (); }Private Static  class MyThread extends Thread {MyThread (String name) {Super(name); }@Override         Public void Run() {inti =0; while(I++ <6) {//"Thread name" + "-" + "ordinal"String val = Thread.CurrentThread (). GetName () +i; Queue.add (Val);//Traverse the queue through "Iterator". Printall (); }        }    }}

No error when using Concurrentlinkedqueue

An error occurred while using LinkedList:

Copyright NOTICE: This article for Bo Master original article, reproduced please indicate the source, view the original article, please visit: Http://blog.csdn.net/xingjiarong

Java Multithreading (10) using a thread-safe collection

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.