Application of Abstractqueuedsynchronizer in tool class Reentrantlock, semaphore, Countdownlatch and Cyclicbarrier _ concurrent programming

Source: Internet
Author: User
Tags semaphore

In the Java.util.concurrent package, the application of Abstractqueuedsynchronizer is very extensive, but not limited to the implementation in Reentrantlock, this article briefly introduces the Abstractqueuedsynchronizer in Semap Applications in Hore, Countdownlatch, Reentrantreadwritelock and other classes.

0. Recalls

In the introduction of Aqs, the sync subclasses in the Aqs and Reentrantlock classes were introduced to implement the Reentrant locks, in which Aqs provided a flexible and complete queue processing mechanism. Since the complete queue processing mechanism has been provided in Aqs, it is often not necessary to extend the subclass override. At the same time, AQS provides the state attribute and the Tryacquire ()/tryrelease (), and these are the extension points that need to be flexibly implemented by subclasses according to the specific requirements logic. From the implementations of Reentrantlock, Reentrantreadwritelock, Semaphore, and Countdownlatch, it is common to encapsulate your own unique sync inner classes in these tool classes. And sync is the extension implementation of AQS.

1. Semaphore

When learning the theory of operating system class, the textbook should be talked about the concept of semaphore, Java.util.concurrent.Semaphore class is the Java concept of the implementation. For example, a resource R has 5 entities, if 1 are required for each thread to execute, 5 threads are allowed to execute concurrently, and the 6th waits for the other thread to release the resource and continue execution.

Let's look at an example of an application semaphore:
One of the most important methods is acquire () and release (), which can be consulted in more detail in Oracle's API documentation.

Executorservice exec = Executors.newcachedthreadpool ();
        Finalsemaphore sem = newsemaphore (5);
 
        for (inti = 1; i < i++) {
            Finalint tid = i;
            Runnable semtask = newrunnable () {
                publicvoid run () {
                    try{
                        sem.acquire ();
 
                        SYSTEM.OUT.PRINTLN ("Running Thread with ID:" + tid);
                        Thread.Sleep ((Long) (Math.random () * 3000));
                        System.out.println ("Completing with ID:" + tid);
 
                        Sem.release ();
                    } catch (Interruptedexception e) {
                        e.printstacktrace ();}}}
            ;
            Exec.execute (Semtask);
        }
        Exec.shutdown ();

Here's a look at the semaphore implementation. If you are familiar with the implementation of Reentrantlock, then semaphore in fact very good understanding, in simple terms, semaphore is actually the lock limit from 1 to N.

State stores values that represent the remaining available resources node uses the shared mode to acquire the lock and then try to propagate, releasing more locks

2. Countdownlatch

This class is primarily designed to solve the problem of state dependencies in multiple threads. Java.util.concurrent.CountDownLatch This class from the name can be seen, is based on a descending counter, multiple threads share such an object, open a count value, some threads can wait for this counter value of 0 to continue the task, call await () and those that change the state need to do is decrement the counter and invoke the countdown () method.

Executorservice exec = Executors.newcachedthreadpool ();
 
        Finalcountdownlatch CDL = Newcountdownlatch (3); Runnable watingtasks = newrunnable () {Publicvoidrun () {try{SYSTEM.OUT.P Rintln ("There ' re 3 tasks here.")
                    If all tasks are finished, I'll go home. ");
 
                    System.out.println ("Working ...");
 
                    Cdl.await ();
                System.out.println ("OK, I'll go Home now!");
                }catch (interruptedexception e) {e.printstacktrace ();
        }
            }
        };
 
        Exec.execute (Watingtasks);
            for (inti = 0; i < 3; i++) {finalinttid = i; Runnable semtask = newrunnable () {Publicvoidrun () {try{Syst
                        EM.OUT.PRINTLN ("Starting task" + Tid + "...");
                        Thread.Sleep ((Long) (Math.random () * 5000)); System.OUT.PRINTLN ("task" + Tid + "finished");
 
                    Cdl.countdown ();
                    }catch (interruptedexception e) {e.printstacktrace ();
            }
                }
            };
        Exec.execute (Semtask); } exec.shutdown ();

Similar to semaphore, in the use of AQS implementation, there are mainly the following points.

State stores the Count count variable node is using the shared mode countdown () call tryreleaseshared make the count minus 1 await is called Tryacquire, which is actually to determine whether the state is 0

3. Reentrantreadwritelock

In high concurrency scenarios, it is necessary to separate read and write scenarios in order for the task to perform more efficiently. This is because of the different characteristics of reading and writing thread security, reading does not change the state, multiple threads can be done at the same time without problems, while writing and writing, writing and reading are mutually exclusive. In Java.util.concurrent, Reentrantreadwritelock is the kind of thing that does this.

The specific use is not an example, the direct analysis of its implementation. Reentrantlock and Reentrantreadwritelock are similar from class names, and there are similar parts to implementations. The Readlock and Writelock inner classes are encapsulated in the Reentrantreadwritelock, while Reentrantreadwritelock, Reentrantreadwritelock.readlock, Reentrantreadwritelock.writelock have their own sync class properties, using the Reentrantreadwritelock.sync implementation, and the object relationship, Readlock and writelock in the sync are pointing to the reent The sync reference in the Rantreadwritelock object, that is, the same set of queues using the same Aqs, except that the method is separated from processing.

The main points: State stores both R and W number Writelock lock operations are similar to Reentrantlock using mutexes and readlock using shared nodes to read locks in their respective trylock, Finally realized in the Tryreadlock and Trywritelock of Readwritelock

4. Cyclicbarrier

To say Java.util.concurrent.CyclicBarrier here is not because it uses AQS, but because its usage and countdownlatch have similarities. Both Cyclicbarrier and Countdownlatch are dealing with state dependencies, but the difference is that the threads that use cyclicbarrier depend on each other, waiting for each other until a certain state is reached, and those threads continue to execute at the same time.

Cyclicbarrier is based on Reetrantlock and Conditionobject, await () when the counter is decremented and checked for 0, If 0 executes the Barriercommand (Runnable Class object property) of the Cyclicbarrier class object and Signalall () notifies all waiting threads to start the next round, otherwise blocking the current thread.

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.