Example usage for org.apache.zookeeper ZooKeeper transaction

List of usage examples for org.apache.zookeeper ZooKeeper transaction

Introduction

In this page you can find the example usage for org.apache.zookeeper ZooKeeper transaction.

Prototype

public Transaction transaction() 

Source Link

Document

A Transaction is a thin wrapper on the #multi method which provides a builder object that can be used to construct and commit an atomic set of operations.

Usage

From source file:org.apache.bookkeeper.zookeeper.BkZooKeeperClient.java

License:Apache License

@Override
@Deprecated//  w  w  w. ja v a  2  s  .c  o m
public Transaction transaction() {
    // since there is no reference about which client that the transaction could use
    // so just use ZooKeeper instance directly.
    // you'd better to use {@link #multi}.
    ZooKeeper zkHandle = zk.get();
    if (null == zkHandle) {
        return super.transaction();
    }
    return zkHandle.transaction();
}

From source file:org.apache.distributedlog.service.placement.ZKPlacementStateManager.java

License:Apache License

@Override
public void saveOwnership(TreeSet<ServerLoad> serverLoads) throws StateManagerSaveException {
    logger.info("saving ownership");
    try {//  w  w w.ja v a2  s . c  o  m
        ZooKeeper zk = zkClient.get();
        // use timestamp as data so watchers will see any changes
        byte[] timestamp = ByteBuffer.allocate(8).putLong(System.currentTimeMillis()).array();

        if (zk.exists(serverLoadPath, false) == null) { //create path to rootnode if it does not yet exist
            createServerLoadPathIfNoExists(timestamp);
        }

        Transaction tx = zk.transaction();
        List<String> children = zk.getChildren(serverLoadPath, false);
        HashSet<String> servers = new HashSet<String>(children);
        tx.setData(serverLoadPath, timestamp, -1); // trigger the watcher that data has been updated
        for (ServerLoad serverLoad : serverLoads) {
            String server = serverToZkFormat(serverLoad.getServer());
            String serverPath = serverPath(server);
            if (servers.contains(server)) {
                servers.remove(server);
                tx.setData(serverPath, serverLoad.serialize(), -1);
            } else {
                tx.create(serverPath, serverLoad.serialize(), zkClient.getDefaultACL(), CreateMode.PERSISTENT);
            }
        }
        for (String server : servers) {
            tx.delete(serverPath(server), -1);
        }
        tx.commit();
    } catch (InterruptedException | IOException | KeeperException e) {
        throw new StateManagerSaveException(e);
    }
}