Java concurrent containers and frameworks

Source: Internet
Author: User

1.concurrenthashmap1.1 why using Concurrenthashmap to use HASHMAP in concurrent programming can cause the program to die in a loop. The use of thread-safe hashtable efficiency is very low, based on the above two reasons, there is a chance of Concurrenthashmap debut. (1) thread insecure hashmap in a multithreaded environment, using HASHMAP for put operations can cause a dead loop, resulting in a CPU utilization of nearly 100%. The reason is that when the table is expanded, it is easy to form a chain (2) inefficient hashtablehashtable container using synchronized to ensure thread safety, but Hashtable is inefficient in the case of intense online competition. Because when a thread accesses the Hashtable synchronization method, other threads also access the Hashtable synchronization method, which goes into blocking or polling state. If thread 1 uses put for element addition, thread 2 cannot use the Put method to add elements or use the Get method to get elements, so the more intense the competition the less efficient. (3) Concurrenthashmap Lock segmentation technology can effectively increase the concurrent access rate Hashtable containers are inefficient in a competitive concurrency environment because all access Hashtable threads must compete for the same lock, if there are multiple locks in the container, Each lock is used to lock the container part of the data, then when the multi-threaded access to different data segments in the container data, there will be no lock competition between the threads, which can effectively improve the efficiency of concurrent access, which is the lock segmentation technology used by Concurrenthashmap. First, the data is divided into a section of storage, and then to each piece of data with a lock, when a thread occupies a lock to access one of the data, other segments of the data can also be accessed by other threads. The structure Concurrenthashmap of 1.2 concurrenthashmap is composed of segment array structure and hashentry array structure. Segment is a reentrant lock (Reentrantlock) that plays the role of a lock in Concurrenthashmap; Hashentry is used to store key-value pairs of data. A concurrenthashmap contains an array of segment. The structure of segment is similar to HashMap, and it is an array and a linked list structure. A segment contains an array of hashentry, each of which is an element of a list structure, each segment guarding an element in a hashentry array, and when the data of the Hashentry array is modified, Must first obtain the SEG corresponding to itment lock, shown in 1-2.

 

The efficiency of the 1.3.get operation get operation is that the entire get procedure does not need to be locked, unless the read value is null to lock and reread. We know that the Get method of the Hashtable container needs to be locked, so how does the Concurrenthashmap get operation do not lock? The reason is that the shared variable that will be used in its Get method is defined as a volatile type, such as the Count field used to count the current segement size and the value of the hashentry used for storage. Variables defined as volatile, able to maintain visibility between threads, can be read at the same time, and guaranteed not to read expired values, but can only be single-threaded write (there is a case can be multi-threaded writing, that is, the value written is not dependent on the original value), In the get operation only need to read not to write the shared variable count and value, so you can not lock. The expiration value is not read because, according to the happen before principle of the Java memory model, write operations on volatile fields precede the read operation, even if two threads modify and get the volatile variable at the same time, the get operation can get the most recent value. This is a classic application scenario for volatile replacement locks. 1.4put operation because of the need to write to shared variables in the Put method, for thread safety, you must lock the shared variable when it is being manipulated. The Put method first navigates to the segment and then inserts in the segment. The insert operation takes two steps, the first step is to determine if the Hashentry array in segment needs to be expanded, the second step is to position the element, and then place it in the hashentry array. (1) How to enlarge. When you expand, you first create an array with a capacity of twice times the original capacity, and then re-hash the elements in the original array into the new array. To be efficient, CONCURRENTHASHMAP does not scale the entire container, but only one segment. 1.51.5.size operation if you want to count the size of the elements in the entire concurrenthashmap, you must count all the elements in the segment and sum them. Segment the global variable count is a volatile variable, then in the multi-threaded scenario, is not directly all the segment count is added to get the entire concurrenthashmap size? No, although it is possible to get the latest value of the count of each segment when it is added, the count may not be counted until it has changed. Therefore, the safest way to do this is to keep all segment's put, remove, and clean sides when the size is counted.The law is locked, but it is obviously very inefficient. Because in the cumulative count operation, the probability of the previous cumulative count change is very small, so the Concurrenthashmap practice is to first try 2 times by not locking segment way to count the size of each segment, if the process of statistics, When the container's count changes, the lock is used to count the size of all segment. So how does concurrenthashmap determine if the container has changed at the time of the statistic? With the Modcount variable, the variable modcount is added 1 before the element is manipulated in the put, remove, and clean methods, so whether the size of the container changes before and after the statistic size is modcount. 2 Concurrentlinkedqueue a link node-based, non-blocking routing secure queue using a nonblocking algorithm that uses FIFO rules to sort the nodes, and when we add an element, it is added to the tail of the queue; when we get an element, It returns the element at the head of the queue. It uses the "Wait-free" algorithm (CAS algorithm) to achieve  

Both the team and the squad do not immediately update the head and Tair pointers: Find the queue to do two things: the first is to set the queued node to the next node of the current tail node, the second is to update the tail node, if the tail node's next node is not empty, the queue node is set to tail node, If the next node of the tail node is empty, the queued node is set to the next node of tail, so the tail node is not always the end section 3 what is the blocking queue blocking queue (Blockingqueue) is a queue that supports two additional operations. Both of these additional operations support blocking insertion and removal methods. 1) Blocking insertion method: means that when the queue is full, the queue blocks the thread that inserted the element until the queue is dissatisfied. 2) Blocking removal method: means that the thread that gets the element waits for the queue to become non-empty when the queue is empty.

• Throws an exception: when the queue is full, the IllegalStateException ("Queuefull") exception is thrown if the element is inserted into the queue. When the queue is empty, fetching elements from the queue throws nosuchelementexception exceptions. • Returns a special value: Returns True if the element is inserted successfully when the element is inserted toward the queue. If the method is removed, an element is fetched from the queue and null if none is returned. • Always block: When the blocking queue is full, if the producer thread puts elements into the queue, the queue will block the producer thread until the queue is available or the response is interrupted to exit. When the queue is empty, if the consumer thread takes elements from the queue, the queue blocks the consumer thread until the queue is not empty. • Timeout exit: When the blocking queue is full, if the producer thread inserts elements into the queue, the queue blocks the producer thread for a period of time, and if the specified time is exceeded, the producer thread exits. JDK 7 provides 7 blocking queues, as follows. Arrayblockingqueue: A bounded blocking queue consisting of an array structure. Linkedblockingqueue: a bounded block queue consisting of a list structure. Priorityblockingqueue: A unbounded blocking queue that supports priority ordering. Delayqueue: An unbounded blocking queue implemented with a priority queue. Synchronousqueue: A blocking queue that does not store elements. LinkedTransferQueue: An unbounded blocking queue consisting of a linked list structure. Linkedblockingdeque: A two-way blocking queue consisting of a linked list structure. The 4.fork/join Framework Fork/join Framework is a framework that Java 7 provides for parallel execution of tasks, a framework that divides large tasks into small tasks, and ultimately summarizes the results of a large task after each small task. 1. Work-stealing (work-stealing) means that a thread steals a task from another queue to execute it. Instead of waiting for a live thread to work with other threads, it goes to another thread's queue to steal a task to execute. At this point they will be accessing the same queue, so in order to reduce the contention between the stealing task thread and the stolen task thread, a double-ended queue is usually used, the stolen task thread will always execute from the head of the double-ended queue, and the thread that steals the task will always carry the task from the tail of the double-ended queue. Advantages: The full use of threads for parallel computing, reducing the competition between threads. Cons: In some cases there is still competition, such as when there is only one task in the double-ended queue. Andand the algorithm consumes more system resources, such as creating multiple threads and multiple double-ended queues. The 2.java implementation Fork/join uses two classes to accomplish both of these things. ①forkjointask: To use the Forkjoin framework, you must first create a forkjoin task. It provides a mechanism for performing fork () and join () operations in a task. Typically, we do not need to inherit the Forkjointask class directly, only to inherit its subclasses, the Fork/join framework provides the following two subclasses. • Recursiveaction: Used for tasks that do not return results. Recursivetask: Used for tasks that have return results. ②forkjoinpool:forkjointask need to be executed through Forkjoinpool.
 Public classCounttaskextendsRecursivetask<integer> {    Private Static Final intTHRESHOLD = 2;//threshold Value    Private intstart; Private intend;  PublicCounttask (intStartintend) {         This. Start =start;  This. end =end; }    protectedInteger Compute () {intsum = 0;//Calculate tasks If the task is small enough        BooleanCancompute = (End-start) <=THRESHOLD; if(cancompute) { for(inti = start; I <= end; i++) {sum+=i; }        } Else {//if the task is greater than the threshold, it is split into two sub-task calculations            intMiddle = (start + end)/2; Counttask Lefttask=Newcounttask (start, middle); Counttask Righttask=NewCounttask (middle + 1, end);//To perform sub-taskslefttask.fork (); Righttask.fork ();//wait for the subtasks to finish and get their results            intleftresult=Lefttask.join (); intrightresult=Righttask.join ();//To Merge sub-taskssum = Leftresult +Rightresult; }        returnsum; }    Static  Public  voidTest () {Forkjoinpool Forkjoinpool=NewForkjoinpool ();//generate a compute task that calculates 1+2+3+4Counttask task =NewCounttask (1, 40000);//Perform a taskfuture<integer> result =Forkjoinpool.submit (Task); Try{System.out.println (Result.get ()); } Catch(Interruptedexception e) {}Catch(Executionexception e) {} }}

Java concurrent containers and frameworks

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.