Java Learning Notes-multithreading (synchronization containers and concurrent containers)

Source: Internet
Author: User
Tags new set

Brief introduction of synchronization container and concurrent container

In Java concurrent programming, often hear the synchronization container, the concurrent container is said, what is the synchronization container and the concurrent container? A synchronization container can simply be understood as a container that implements synchronization via synchronized, such as vectors, Hashtable, and synchronizedlist, and if multiple threads invoke the method of synchronizing the container, they will be executed serially.

By looking at the implementation code of the synchronization containers such as vectors and Hashtable, you can see how these containers implement thread safety by encapsulating their state and adding keyword synchronized to the methods that require synchronization, but in some cases Synchronizing a container is not necessarily thread-safe, such as getting the last element or deleting the last element, we need to implement additional synchronization operations:

 Public Static Object getlast (Vector list) {      int lastIndex = list.size ()-1;       return List.get (LastIndex);  }          Public Static void deletelast (Vector list) {      int lastIndex = list.size ()-1;      List.remove (LastIndex);  

Although the above approach does not seem to be a problem, Vector's own methods are synchronous, but the problem is hidden in multithreaded environments. If there are two threads, A/b, which calls the two methods above, assuming that the list size is 10, the calculated lastindex is 9, and thread B first performs the delete operation (the uncertainty caused by the execution of the operation between multithreading), When thread A calls the List.get method, an array out-of-bounds exception occurs, causing the problem because the composite operation above is not an atomic operation, which can be done by using a list object lock inside the method.

Synchronizing containers can result in serial execution of container method calls in multiple threads, reducing concurrency because they are locks on the container's own object, so in environments where concurrency is required, consider using concurrent containers instead. Concurrent containers are designed for concurrent access to multiple threads, and the concurrent package is introduced in jdk5.0, which provides many concurrent containers, such as Concurrenthashmap, Copyonwritearraylist, and so on.

In fact, both the synchronization container and concurrent container provide the appropriate thread security for multi-threaded concurrent access, but the concurrency container is more extensible. Before JAVA5, programmers only synchronize containers, and when multi-threaded concurrent access can lead to contention, hindering the system's extensibility. JAVA5 introduces concurrent containers, which use a completely different locking strategy from the synchronization container to provide higher concurrency and scalability, for example, a finer-grained locking mechanism in concurrenthashmap, which can be called a segmented lock, in which the lock mechanism Allows any number of read threads to access the map concurrently, and the thread that performs the read operation and the thread that writes the operation can also access the map concurrently, allowing a certain number of write threads to modify the map concurrently, so that it can achieve higher throughput in a concurrent environment, plus Concurrent containers provide a number of composite operations that require their own implementation when using a synchronization container, including Putifabsent, but because concurrent containers cannot be exclusively accessed by locking, we cannot add locks to implement other composite operations.

Concurrent containers

From the above analysis we know that the synchronization container does not guarantee multithreading security, and concurrent containers are designed for concurrent access to multiple threads, in jdk5.0 introduced the concurrent package, which provides a lot of concurrent containers, greatly improving the performance of the synchronization container class.

Concurrenthashmap
    • Corresponding non-concurrent containers: HashMap
    • Target: Replace Hashtable, Synchronizedmap, support compound operation
    • Principle: JDK6 uses a more fine-grained locking mechanism segment "segmented lock", JDK8 using CAS lock-free algorithm, detailed analysis recommended reading "JDK": concurrenthashmap high concurrency mechanism-"reprint".
Copyonwritearraylist
    • Corresponding non-concurrent containers: ArrayList
    • Target: Instead of vector, synchronizedlist
    • Principle: The use of high concurrency is often read and write less features, do not lock the read operation, the write operation, first copy a new set, in the new set above the modification, and then assign the new set to the old reference, and through the volatile to ensure its visibility, of course, write operation of the lock is essential.

For this part can refer to "JDK": copyonwritearraylist, Copyonwritearrayset source parsing

Copyonwritearrayset
    • Corresponding fee concurrent container: HashSet
    • Goal: Replace Synchronizedset
    • Principle: Based on the copyonwritearraylist implementation, the only difference is that when add is called the Copyonwritearraylist Addifabsent method, which iterates through the current object array, such as the object array already has the current element , it is returned directly, and if not, it is placed at the end of the object array and returned.

For this part can refer to "JDK": copyonwritearraylist, Copyonwritearrayset source parsing

Concurrentskiplistmap
    • Corresponding non-concurrent containers: TreeMap
    • Objective: To replace Synchronizedsortedmap (TREEMAP)
    • Principle: Skip list (skip table) is a data structure that can be used instead of a balanced tree, by default ascending by key value. The Skip list allows the sorted data to be distributed in a multi-level linked list, with 0-1 random numbers determining whether a data climbs up or down, through "space for Time" algorithm. Concurrentskiplistmap provides a sort of thread-safe, concurrent-access sorting mapping table. Internal is the Skiplist (jump table) structure implementation, in theory can be in the O (log (n)) time to complete the search, insert, delete operations.
Concurrentskiplistset
    • Corresponding non-concurrent containers: TreeSet
    • Goal: Replace Synchronizedsortedset
    • Principle: Internally based CONCURRENTSKIPLISTMAP implementation
Concurrentlinkedqueue

Queues that do not block

    • Corresponding non-concurrent containers: Queue
    • Principle: FIFO queue based on linked list (concurrent version of LinkedList)
Linkedblockingqueue, Arrayblockingqueue, Priorityblockingqueue
      • Corresponding non-concurrent containers: Blockingqueue
      • Features: Expanded queue, increased blocking insertion and acquisition operations
      • Principle: Thread safety through reentrantlock, blocking and waking through condition
      • Implementation class:
        • Linkedblockingqueue: A blocking FIFO queue based on linked list implementation
        • Arrayblockingqueue: A blocking FIFO queue based on an array implementation
        • Priorityblockingqueue: Queues sorted by priority

Reference:

Java Concurrency: Synchronizing containers & Concurrent containers

"JDK": Java Container Framework--synchronization container and concurrent container

Java Learning Notes-multithreading (synchronization containers and concurrent containers)

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.