This is a prerelease version.

View latest

ICountDownLatch

Hazelcast ICountDownLatch is the distributed implementation of java.util.concurrent.CountDownLatch. But unlike Java’s implementation, Hazelcast’s ICountDownLatch count can be reset after a countdown has finished, but not during an active count.

This data structure is a member of the CP Subsystem. By default, the CP Subsystem is in unsafe mode, which provides weaker consistency guarantees. You can enable the CP Subsystem in the member configuration.

Gate-Keeping Concurrent Activities

ICountDownLatch is considered to be a gatekeeper for concurrent activities. It enables the threads to wait for other threads to complete their operations. The following examples describe the mechanism of ICountDownLatch.

Assume that there is a leader process and there are follower processes that will wait until the leader completes. Here is the leader:

public class Leader {
    public static void main( String[] args ) throws Exception {
        HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
        ICountDownLatch latch = hazelcastInstance.getCPSubsystem().getCountDownLatch( "countDownLatch" );
        System.out.println( "Starting" );
        latch.trySetCount( 1 );
        Thread.sleep( 30000 );
        latch.countDown();
        System.out.println( "Leader finished" );
        latch.destroy();
    }
}

Since only a single step is needed to be completed as a sample, the above code initializes the latch with 1. Then, the code sleeps for a while to simulate a process and starts the countdown. Finally, it clears up the latch. Let’s write a follower:

public class Follower {
    public static void main( String[] args ) throws Exception {
        HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
        ICountDownLatch latch = hazelcastInstance.getCPSubsystem().getCountDownLatch( "countDownLatch" );
        System.out.println( "Waiting" );
        boolean success = latch.await( 10, TimeUnit.SECONDS );
        System.out.println( "Complete: " + success );
    }
}

The follower class above first retrieves ICountDownLatch and then calls the await method to enable the thread to listen for the latch. The method await has a timeout value as a parameter. This is useful when the countDown method fails. To see ICountDownLatch in action, start the leader first and then start one or more followers. You will see that the followers wait until the leader completes.

ICountDownLatch s are not automatically removed. If a latch is not used anymore, Hazelcast does not automatically perform garbage collection in it. This can lead to an OutOfMemoryError. If you create ICountDownLatchs on the fly, make sure they are destroyed. See Destroying Objects and CP Data Structures.