Skip to content

Instantly share code, notes, and snippets.

@Randgalt
Created September 21, 2019 15:45
Show Gist options
  • Save Randgalt/1a19dcd215e202936e5b92c121fc73de to your computer and use it in GitHub Desktop.
Save Randgalt/1a19dcd215e202936e5b92c121fc73de to your computer and use it in GitHub Desktop.
package org.apache.curator.framework.recipes.leader;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.transaction.CuratorOp;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects;
public class LeaderTransaction
{
private final Logger log = LoggerFactory.getLogger(getClass());
private final CuratorFramework client;
private final String coordinationPath;
private volatile int savedVersion;
public LeaderTransaction(CuratorFramework client, String coordinationPath)
{
this.client = Objects.requireNonNull(client, "client cannot be null");
this.coordinationPath = Objects.requireNonNull(coordinationPath, "coordinationPath cannot be null");
}
public boolean setLeader()
{
try
{
Stat stat = client.checkExists().forPath(coordinationPath);
if ( stat == null )
{
client.create().creatingParentContainersIfNeeded().forPath(coordinationPath);
savedVersion = 0;
}
else
{
savedVersion = stat.getVersion();
}
stat = client.setData().withVersion(savedVersion).forPath(coordinationPath);
savedVersion = stat.getVersion();
}
catch ( KeeperException.BadVersionException e )
{
log.debug("setLeader failed due to bad version", e);
return false;
}
catch ( Exception e )
{
log.debug("setLeader failed", e);
return false;
}
return true;
}
public CuratorOp transactionOp()
{
try
{
return client.transactionOp().check().withVersion(savedVersion).forPath(coordinationPath);
}
catch ( Exception e )
{
// should never happen
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment