final CountDownLatch timesSquare = new CountDownLatch(PARTICIPANT_QTY);
final AtomicLong masterCounter = new AtomicLong(0);
final AtomicLong notLeaderCounter = new AtomicLong(0);
Timing timing = new Timing();
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
ExecutorService exec = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setDaemon(true).setNameFormat("callbackNotifyLeader-%s").build());
List<LeaderLatch> latches = Lists.newArrayList();
for ( int i = 0; i < PARTICIPANT_QTY; ++i )
{
LeaderLatch.CloseMode closeMode = i < SILENT_QTY ? LeaderLatch.CloseMode.SILENT : LeaderLatch.CloseMode.NOTIFY_LEADER;
final LeaderLatch latch = new LeaderLatch(client, PATH_NAME, "", closeMode);
latch.addListener(new LeaderLatchListener()
{
boolean beenLeader = false;
@Override
public void isLeader()
{
if ( !beenLeader )
{
masterCounter.incrementAndGet();
beenLeader = true;
try
{
latch.reset();
}
catch ( Exception e )
{
throw Throwables.propagate(e);
}
}
else
{
masterCounter.incrementAndGet();
CloseableUtils.closeQuietly(latch);
timesSquare.countDown();
}
}
@Override
public void notLeader()
{
notLeaderCounter.incrementAndGet();
}
}, exec);
latches.add(latch);
}
try
{
client.start();
for ( LeaderLatch latch : latches )
{
latch.start();
}