Java thread (14th): A Powerful Concurrent collection class in the Concurrent package

Source: Internet
Author: User

Collection classes, such as ArrayList and HashMap, are frequently used to write programs. However, these sets cannot implement the concurrent operation mechanism, which consumes resources and wastes time when running on the server, you cannot perform operations on these sets during iteration. Otherwise, an error occurs, such as the following program:
[Java]
Public class CollectionModifyExceptionTest {
Public static void main (String [] args ){
Collection users = new ArrayList ();
Users. add (new User ("James", 28 ));
Users. add (new User ("Li Si", 25 ));
Users. add (new User ("Wang Wu", 31 ));
Iterator itrUsers = users. iterator ();
While (itrUsers. hasNext ()){
System. out. println ("running! ");
User user = (User) itrUsers. next ();
If ("Li Si". equals (user. getName ())){
Users. remove (user );
} Else {
System. out. println (user );
}
}
}
}
An error is reported during the execution of the program because an ArrayList collection is defined, but the users occurs again when the collection is iterated. remove (user): deletes data from a set. This is not allowed for a Common set, java 5 and later concurrent collection classes are specifically designed for general sets that cannot be concurrent and cannot be used to modify data during iteration.

Concurrent collection classes mainly include:
ConcurrentHashMap; ConcurrentSkipListMap; ConCurrentSkipListSet; CopyOnWriteArrayList; CopyOnWriteArraySet; concurrent1_queue;

Some of the following collection classes are briefly described:

ConcurrentHashMap supports fully concurrent retrieval and updating of the expected adjustable concurrent hash table. This class complies with the same functional specifications as Hashtable and includes the method versions corresponding to each method of Hashtable. However, although all operations are thread-safe, the search operation is not required to lock the entire table and does not support locking the entire table in a way that prevents all access. This class can be fully interoperable with Hashtable through the program, depending on its thread security, and has nothing to do with the synchronization details.
The main constructor methods include:
[Java]
ConcurrentHashMap (); // creates a new empty ing with the default initial capacity, load factor, and concurrencyLevel.
ConcurrentHashMap (int initialCapacity); // creates a new empty ing with the specified initial capacity, default load factor, and concurrencyLevel.
ConcurrentHashMap (int initialCapacity, float loadFactor, int concurrencyLevel); // creates a new empty ing with the specified initial capacity, load factor, and concurrency level.
ConcurrentHashMap (Map <> t); // construct a new ing with the same ing relationship as the given ing.

Concurrentincluqueue is a connection-node-based, unbounded, thread-safe queue. This queue sorts the elements according to the FIFO (first-in-first-out) principle. The queue header is the longest element in the queue. The tail of a queue is the minimum time element in the queue. Insert new elements to the end of the queue, and retrieve the elements from the queue header. When multiple threads share access to a public collection, concurrentincluqueue is an appropriate choice. This queue does not allow null elements.
The main constructor methods include:
[Java]
Concurrentincluqueue (); // create a initially empty concurrentincluqueue.
Concurrentincluqueue (Collection <> c); // create a concurrentincluqueue that initially contains the elements of the given collection, and add the elements in the traversal order of this collection iterator

CopyOnWriteArrayList is a thread-safe deformation of ArrayList. All variable operations (ADD, set, and so on) are implemented through a new copy of the basic array. This usually requires a lot of overhead. However, when the number of traversal operations exceeds the number of variable operations, this method may be more effective than other alternative methods. It is also useful when you cannot or do not want to perform synchronous traversal, but you need to exclude conflicts from the concurrent threads. The Snapshot-style iterator method uses references to the array status when creating the iterator. This array will never be changed during the lifetime of the iterator, so there is no possibility of conflict, and the iterator will not throw ConcurrentModificationException. After an iterator is created, the iterator does not reflect the addition, removal, or modification of the list. Changing elements on the iterator (removing, setting, and adding) is not supported ). These methods will throw UnsupportedOperationException.
The main constructor methods include:
[Java]
CopyOnWriteArrayList (); // create an empty list.
CopyOnWriteArrayList (Collection <> c); // create a list of elements that contain the specified Collection in the order returned by the Collection iterator.
CopyOnWriteArrayList (E [] toCopyIn); // create a new CopyOnWriteArrayList, which keeps copies of the given array.

CopyOnWriteArraySet is the Set that uses CopyOnWriteArrayList for all its operations. Therefore, it shares the following basic attributes:
It is most suitable for applications where the set SIZE is usually small, the read-only operation is much larger than the variable operation, and the inter-thread conflict needs to be prevented during traversal.
It is thread-safe.
Because the entire basic array needs to be copied, the overhead of variable operations (adding, setting, removing, and so on) is huge.
The iterator does not support variable removal.
Traversal using the iterator is fast and does not conflict with other threads. When constructing the iterator, The iterator depends on the unchanged array snapshot.
The main constructor methods include:
[Java]
CopyOnWriteArraySet (); // create an empty set
CopyOnWriteArraySet (Collection <> c); // creates a set that contains all the elements of the specified Collection.


After the concurrent Collection class is finished, return to the example at the beginning of this article. If you rewrite Collection users = new ArrayList () to Collection users = new CopyOnWriteArrayList (), then run the program, the program runs normally. The result is as follows:
[Java]
Executing!
{Name: 'zhang san', age: 28}
Executing!
Executing!
{Name: 'wang 5', age: 31}


 

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.