Java concurrency Countdownlatch, cyclicbarrier, and semaphore

Source: Internet
Author: User

Countdownlatch is the ability to keep a group of threads waiting for another set of threads to run and run; Cyclicbarrier enables a set of threads to synchronize at one point in time, starting with all or part of a task together.

The three Countdownlatch, Cyclicbarrier, and Semaphore are the more commonly used Synchronizer in JUC, which makes it easy to implement the functionality of collaboration among many threads.

Countdownlatch

The literal translation comes down to the counting (countdown) latch (Latch). Pour count Needless to say, the meaning of the latch is to prevent progress. This means that the countdownlatch.await () method blocks the current thread before the inverted count is 0.

Role

The Countdownlatch function is similar to the Thread.Join () method, and can be used for collaboration between a set of threads and another set of threads. For example, the main thread needs a series of preparatory work before doing a job, and the main thread can continue its work only if the preparation is complete. These preparations are independent of each other, so they can be executed concurrently to increase speed. In this scenario, you can use countdownlatch to coordinate the scheduling between threads. We can use Thread.Join () at the time of creating threads directly (before Java 5.0). After JUC appears, you must use Countdownlatch because the threads in the thread pool are not directly referenced.

Example

The following example can be understood as the F1 car repair process, only startsignal (can indicate parking, may not be the same name) after the command issued, the maintenance workers began to work, only after all the workers to complete the work, the car can continue.

Class Driver {//... void main () throws Interruptedexception {Countdownlatch startsignal = new Countdownla          TCH (1);           Countdownlatch donesignal = new Countdownlatch (N); for (int i = 0; i < N; ++i)//Create and start Threads new Thread (New Worker (Startsignal, Donesignal)). St           Art ();            Dosomethingelse ();      Don ' t let run yet startsignal.countdown ();          Let all threads proceed dosomethingelse ();           Donesignal.await ();      Wait for all to finish}} class Worker implements Runnable {private final countdownlatch startsignal;      Private final Countdownlatch donesignal;          Worker (Countdownlatch startsignal, Countdownlatch donesignal) {this.startsignal = startsignal;      This.donesignal = donesignal;              } public void Run () {try {startsignal.await ();              DoWork ();          Donesignal.countdown (); } catch (IntErruptedexception ex) {}//return;  } void DoWork () {...}  }

  

When startsignal.await () blocks a thread, when Startsignal.countdown () is called, all worker threads begin to execute the DoWork () method, so the worker. DoWork () is executed almost at the same time. When Worker.dowork () finishes executing, call Donesignal.countdown () and the main thread continues execution after all worker threads have finished executing.

Cyclicbarrier

Cyclicbarrier is called a circular fence, a circulatory barrier or something (still a bit awkward). So do not translate, imaginative achievement here inexpressible AH). Its main method is one: await (). The await () method is not called once, the count is reduced by 1, and the current thread is blocked. When the count is reduced to 0 o'clock, the blocking is lifted, and all the blocked threads on this cyclicbarrier begin to run. After that, if the await () method is called again, the Count becomes N-1 and the new round starts again, which is what Cyclic means.

The use of cyclicbarrier is not difficult, but it requires the exception that is primarily relevant to it. In addition to the common exceptions, the Cyclicbarrier.await () method throws a unique brokenbarrierexception. This exception occurs when a thread waits for the cyclicbarrier to be interrupted or timed out or reset, and the other threads waiting on the Cyclicbarrier are brokenbarrierexception. It means, comrades, do not wait, there is a small partner has been hung, if we continue to wait may have been waiting, all back home.

The Cyclicbarrier.await () method has a return value that indicates that the current thread is the first thread to reach this Barrier.

As with Countdownlatch, Cyclicbarrier can also set a total value in the constructor. Unlike Countdownlatch, the Cyclicbarrier constructor can also accept a Runnable, which is executed when the Cyclicbarrier is freed.

    1. "The Note:cyclicbarrier function can also be implemented by Countdownlatch.

Example

Cyclicbarrier application (Of course, this example to Countdownlatch can also be achieved, very simple, do not say how to write)

class Solver {final int N;      Final float[][] data;       Final Cyclicbarrier barrier;          Class Worker implements Runnable {int myrow;          Worker (int row) {myrow = row;}                   public void Run () {while (!done ()) {Processrow (myrow);                  try {barrier.await ();                  } catch (Interruptedexception ex) {return;                  } catch (Brokenbarrierexception ex) {return;          }}}} public Solver (float[][] matrix) {data = matrix;          N = Matrix.length;                   Barrier = new Cyclicbarrier (N, New Runnable () {public void run () {mergerows (...);          }              });           for (int i = 0; i < N; ++i) New Thread (New Worker (i)). Start ();      Waituntildone (); }  } 

  

Differences in usage of cyclicbarrier and Countdownlatch

Countdownlatch applies To work collaboration between a set of threads and another main thread. A main thread waits for the task of a group of workers to complete before continuing its execution is the primary scenario for using Countdownlatch; Cyclicbarrier is used for a group or groups of threads, such as a set of threads that need to agree at a point in time, such as starting a job at the same moment. In addition, the cyclic properties of Cyclicbarrier and the Runnable parameters accepted by the constructors are countdownlatch.

Semaphore

Semaphore literal translation is a semaphore, which may be said to be more easily understood by the license volume. Of course, because this name is long-standing in computer science, it can't be changed. Its function is better understood, is to use the constructor to set a number of licenses, and then through the acquire method to obtain permission, release method releases the license. It also has Tryacquire and acquireuninterruptibly methods that can be selected according to your needs.

Example: Semaphore Controlling resource access

Class Pool {private static final int max_available = 100;       Private final Semaphore available = new Semaphore (max_available, true);          Public Object GetItem () throws Interruptedexception {Available.acquire ();      return Getnextavailableitem ();      } public void PutItem (Object x) {if (markasunused (x)) available.release (); }//Not a particularly efficient data structure; Just for demo protected object[] items = ... whatever kinds of items being managed protected boolean[] used = n       EW boolean[max_available];              Protected synchronized Object Getnextavailableitem () {for (int i = 0; i < max_available; ++i) {                  if (!used[i]) {Used[i] = true;              return items[i]; }} return null; Not reached} protected synchronized Boolean markasunused (Object item) {for (int i = 0; i < MAX _available;           ++i) {   if (item = = Items[i]) {if (Used[i]) {Used[i] = false;                  return true;              } else return false;      }} return false;  }  }

  

The use of Semaphore in the above example is nothing to say. The message is that there are two synchronization methods, but there should be no impact on the throughput, because the main thing is to do a Boolean array O (n) operation, and each loop inside the operation is very simple, so fast. But do not know JUC inside the thread pool control is how to do, I am not, have not seen that piece of source code, hollow look, have know can also say.

The last sentence summarizes

Countdownlatch is the ability to keep a group of threads waiting for another set of threads to run and run; Cyclicbarrier enables a set of threads to synchronize at one point in time, starting with all or part of a task together. At the same time, it can be recycled; Semaphore is allowing only a certain number of threads to perform a task at the same time.

Java concurrency Countdownlatch, cyclicbarrier, and semaphore

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.