Skip to content

Instantly share code, notes, and snippets.

@Asitha
Created September 4, 2015 12:28
Show Gist options
  • Save Asitha/a079a0b450e76292fafc to your computer and use it in GitHub Desktop.
Save Asitha/a079a0b450e76292fafc to your computer and use it in GitHub Desktop.
Code snippet to return the leader node in a Hazelcast cluster.
public boolean isLeader() {
// Get all the Hazelcast instances in the current JVM.
// In case of carbon server this is always either one
// or zero.
Iterator<HazelcastInstance> iter
= Hazelcast.getAllHazelcastInstances().iterator();
if (iter.hasNext()) { // cluster mode
HazelcastInstance instance = iter.next();
return instance.getCluster().getMembers().iterator().next().localMember();
} else {
return true; // standalone mode
}
}
@mihai-vasilache
Copy link

At the first look this code looks like is doing nothing valuable, but it should work. Please see this thread:
hazelcast/hazelcast#3760

@Asitha
Copy link
Author

Asitha commented Mar 6, 2022

Newer versions should have better ways... Back in the day (around 2015) we had to get the member list and check whether the first member in the list is a local member. if so, that would mean it is the leader. Other option is to try to capture a distributed lock. But it had to be done carefully... had some issues that I can't recall at the moment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment