Created
September 4, 2015 12:28
-
-
Save Asitha/a079a0b450e76292fafc to your computer and use it in GitHub Desktop.
Code snippet to return the leader node in a Hazelcast cluster.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
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
At the first look this code looks like is doing nothing valuable, but it should work. Please see this thread:
hazelcast/hazelcast#3760