Java Synchronization concurrency Tool classes Countdownlatch, Cyclicbarrier, and semaphore

Source: Internet
Author: User
Tags mutex semaphore

Latching Countdownlatch

Latching is a synchronization tool class that can delay the progress of a thread until it reaches the terminating state. Latching acts as a door: the door is closed until it reaches the end state, and no thread can pass, and when the end state is reached, the door opens and allows all threads to pass. When the latch reaches the end state, it will no longer change its state, so the door remains open forever. Latching can be used to ensure that certain activities do not continue until other activities have been completed, such as:

Make sure that a calculation does not continue until all of the resources it needs are initialized. Binary latching (including two states) can be used to indicate that "resource R has been initialized", and all operations requiring R must now wait on this lockout. Make sure that a service starts only after all other services it relies on are already started. Each service has a related two-dollar lockout. When the service S is started, it will first wait on the lockout of the other services that s relies on, and will release the lockout s when all dependent services are started, so that other services dependent on S can continue to execute. Wait until all participants in an operation (for example, all players in a multi-player game) are ready to resume execution. In this case, when all players are ready, the lockout will reach the end state.

Countdownlatch is a flexible latching implementation that can be used in each of these scenarios, allowing one or more threads to wait for a set of events to occur. The latching state includes a counter that is initialized to a positive number, which indicates how many events need to wait. The countdown method decrements the counter, indicating that an event has occurred, while the await method waits for the counter to reach 0, which means that all events that need to wait have already occurred. If the value of the counter is not 0, then the await is blocked until the counter is 0, or the waiting thread is interrupted, or the wait is timed out.

The following code shows the use of Countdownlatch.

1 ImportJava.util.concurrent.CountDownLatch;2  3 /**4  * @authorBridge5  */6  Public classCountdownlatchtest {7  8  9      Public Static voidMain (string[] args) {Ten         FinalCountdownlatch latch =new Countdownlatch (2); One         NewThread () { A              Public voidrun () { -                 Try { -SYSTEM.OUT.PRINTLN ("Child thread" + thread.currentthread (). GetName () + "executing"); theThread.Sleep (3000); -SYSTEM.OUT.PRINTLN ("Child thread" + thread.currentthread (). GetName () + "executed"); - Latch.countdown (); -}Catch(interruptedexception e) { + e.printstacktrace (); -                 } +             } A }.start (); at   -         NewThread () { -              Public voidrun () { -                 Try { -SYSTEM.OUT.PRINTLN ("Child thread" + thread.currentthread (). GetName () + "executing"); -Thread.Sleep (3000); inSYSTEM.OUT.PRINTLN ("Child thread" + thread.currentthread (). GetName () + "executed"); - Latch.countdown (); to}Catch(interruptedexception e) { + e.printstacktrace (); -                 } the             } * }.start (); $  Panax Notoginseng         Try { -System.out.println ("Wait for 2 sub-threads to finish ..."); the latch.await (); +System.out.println ("2 sub-threads have been executed"); ASystem.out.println ("Continue with the main thread"); the}Catch(interruptedexception e) { + e.printstacktrace (); -         } $     } $   -   -}

The results of the implementation are as follows:

1 child thread thread-0 executing 2 waiting for 2 child threads to finish ... 3 Child thread thread-1 executing 4 child thread thread-0 execution completed 5 child thread thread-1 executed 6 2 Sub-threads have been executed 7 Continue with the main thread

Semaphore

The Count Semaphore (counting Semaphore) is used to control the number of simultaneous accesses to a particular resource, or the number of simultaneous executions of a specified operation. The count semaphore can also be used to implement a resource pool, or to impose boundaries on the container.

A set of virtual licenses is managed in the semaphore, and the initial number of licenses can be specified by constructors, which can be licensed first when the operation is performed, and then released after use. If no license is given to the semaphore, then the acquire will block until it is licensed (or until it is interrupted or the operation times out). The release method returns a license to the semaphore. A simplified form of calculating a semaphore is a two-value semaphore, which is initialized to 1 semaphore. A binary semaphore can be used as a mutex (mutex) and has non-reentrant locking semantics: Whoever owns this unique license has a mutex.

Application Scenarios:

1.Semaphore can be used to implement resource pools, such as database connection pooling. You can construct a fixed-length resource pool. The semaphore count value is initialized to the size of the pool, and the Acquire method is called first to obtain a license before the resource is returned to the pool, and the acquire is blocked until the resource pool is not empty until the pool is fetched.

2. Use semaphore to turn any container into a bounded blocking container. The count value of the semaphore is initialized to the maximum value of the container. The add operation first obtains a license before adding an element to the underlying container. If the add operation does not add any elements, the license is released immediately. Similarly, the remove operation frees a license so that more elements can be added to the container.

1Importjava.util.Collections;2ImportJava.util.HashSet;3ImportJava.util.Set;4ImportJava.util.concurrent.Semaphore;5 6/**7 * Semaphore implements bounded blocking container 8 * 9 *@authorBridge10*/11classBoundedhashset<t> {12Private FinalSet<t>set;13Private FinalSemaphore sem;14 15 PublicBoundedhashset (intbound) {16 This. Set = Collections.synchronizedset (NewHashset<t>());SEM =NewSemaphore (bound);18     }19 20 Public BooleanAdd (T o)throwsinterruptedexception {21st//obtaining a license22Sem.acquire ();23Booleanwasadded =false;24 25Try {wasadded =Set.add (o);27returnwasadded;28}finally {29//If add fails, release the license30if(!wasadded)31sem.release ();32         }33 34     }35 36 Public BooleanRemove (Object o) {37 38Booleanwasremoved =Set.remove (o);39//Release License if removal is successful40if(wasremoved)41sem.release ();42returnwasremoved;43     }44 45 }46 47 Public classBoundedhashsettest {48 49 Public Static voidMain (string[] args) {50FinalBoundedhashset<string> set =NewBoundedhashset<string> (5);51NewThread () {52@Override53 Public voidrun () {System.out.println ("Add");55Try {Set.add ("A");Set.add ("B");Set.add ("C");Set.add ("D");Set.add ("E");Set.add ("F");System.out.println ("Add Complete");63}Catch(interruptedexception e) {64e.printstacktrace ();65                 }66             }67}.start ();68Try {Thread.Sleep (2000);70}Catch(interruptedexception e) {71e.printstacktrace ();72         }73NewThread () {74@Override75 Public voidrun () {System.out.println ("Remove");Set.remove ("A"));78//set.remove ("B");79//set.remove ("F");System.out.println ("Remove complete");81             }82}.start ();83     }84 }85

Run results

Add to

Removed from
Removal complete
Add complete
Cyclicbarrier

Fences (Barrier) are similar to latching, which can block a set of threads until an event occurs. The key difference between fencing and latching is that all threads must reach the fence position at the same time to continue execution. latching is used to wait for events while fences are used to wait for other threads. Fences are used to implement a number of protocols, such as several families deciding to assemble somewhere: "Everyone meets at McDonald's 6:00, waits for someone else later, and then discusses what to do next." ”

Cyclicbarrier can allow a number of participants to gather in the fence position over and over again. The await method is called when the thread reaches the fence position, and this method blocks until all threads reach the fence position. If all the threads have reached the fence position, the fence will open and all the threads will be released, and the fence is reset for the next use. If the call to await times out, or if an await blocking thread is interrupted, the fence is considered broken, and all blocked await calls terminate and throw Brokenbarrierexcepiton.

If the fence is successfully passed, await will return a unique arrival index number for each thread, which we can use to "elect" a leader thread and perform some special work by the lead thread in the next iteration.

Cyclicbarrier also allows you to pass a fence operation to the constructor, which is a runnable that executes when successfully passing a fence (in a subtask thread), but cannot be performed until the blocking thread is freed.

The following example shows the use of Cyclicbarrier.

 1 Import java.util.concurrent.BrokenBarrierException; 2 Import Java.util.concurrent.CyclicBarrier; 3 4/** 5 * @author Bridge 6 */7 public class Cyclicbarriertest {8 9 public static void Main (string[] args) {1 0 int N = 4;11 Cyclicbarrier cyclicbarrier = new Cyclicbarrier (n); (int i = 0; i < N; i++  ) {new Player (Cyclicbarrier). Start (),}15}17,}20 class Player extends Thread {cyclicbarrier cyclicbarrier;24 public Player (Cyclicbarrier cyclicbarrier) {this.cy Clicbarrier = cyclicbarrier;27}28 @Override30 public void Run () {try {THREAD.SL Eep ((Long) (Math.random ())), System.out.println (Thread.CurrentThread () getName () + "Ready!"          "); cyclicbarrier.await (); the catch (Interruptedexception e) {e.printstacktrace (); 37           } catch (Brokenbarrierexception e) {38  E.printstacktrace ();}40 System.out.println (Thread.CurrentThread (). GetName () + "Starting!" "); 41}42}

  

Execution results

thread-1 Ready!
thread-3 Ready! 
thread-2 Ready! 
thread-0 Ready! 
Thread-0 the starting! 
Thread-1 the starting! 
Thread-2 the starting! 
Thread-3 the starting!

Java Synchronization concurrency Tool classes 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.