Synchronizers in Java

Posted By : Pushpandra Kumar | 31-Jan-2019

In Java, by sharing access to fields and objects threads communication is achieved. Thread Interference and memory consistency are some of the issues that result due to thread communication. These issues can be resolved with the help of Synchronization.

However, Latency can be introduced by synchronization, when accessing a lock or object that is currently being held by another thread. Until the other thread releases the lock on the object, the waiting thread cannot use that object. This condition is termed as thread contention.

Java Synchronizers

Five classes for common special-purpose synchronization are provided by Java.

1. CountDownLatch

 In CountdownLatch, One or more threads are set to wait until a set of operations in other threads complete. A count number for no of threads to set for the wait is initialized.

Until the count not reaches zero the await method blocks.

To decrements, the count countDown method is used.

 

2. Semaphores

To restrict thread access to a certain resource, Semaphore is used. A number of permits to a thread are initiated during the creating of the semaphore object.

Until a permit count is not greater than zero, the acquire method blocks and takes it if available and decreases the permit count.

For releasing a blocking acquirer,  release method is used.

 

3. CyclicBarrier

The concept of parties is used byCyclicBarrier on which it is built upon. Until a common barrier point is not reached, it allows threads to wait for each other.

Until all parties have arrived await method blocks. We can say it is the inverse of the CountDownLatch. It continues after N awaits.

 

4. Exchanger

At a point on which two threads can exchange information, the Exchanger acts as a synchronization point. 

Until its counterpart presents its information, threads blocks. The same behavior can be seen on both sides.

 

5. Phaser

Like CountDownLatch and CyclicBarrier, Phaser is a reusable barrier but offers much flexibility.

The number of registered parties is not fixed at creation time in phaser. With the call of the register or bulkRegister methods, any number of parties can be registered at any time. 

To deregister, a party, arriveAndDeregister method can be used.

There is a similarity between some of the methods of CycleBarrierawait method like arriveAndAwaitAdvance.

forceTerminationmethod can use to return all synchronization methods.

About Author

Author Image
Pushpandra Kumar

Pushpender has experience in Core Java, C & C++. His hobbies are learning new technologies and listening music.

Request for Proposal

Name is required

Comment is required

Sending message..