jedli2006
jedli2006

Reputation: 61

can ZooKeeper get znode data and znode data version (stat) in one single operation?

I am developing an application that use ZooKeeper as the datastore. For one of the methods in the application, I need to use the optimistic concurrent control. For example, I need to implement a get method which get the znode data, and I use the znode data version for the optimistic concurrent control check. For what I understand, one can't get the znode data and znode data version in one single operation. If there is high contention to update the znode data, the get method will not work since the znode data might changed after getting the znode data. so I am asking - is there a way I get can the znode data and znode data version (or znode stat) in one single operation without any locking attempt in between?

Upvotes: 6

Views: 3073

Answers (2)

ReneSac
ReneSac

Reputation: 531

In Python using Kazoo it is also trivial to get both stats and implement some optmistic locking. Here a sketch:

while True:
    data, stat = zk.get("/path")
    # do something with the data and then:
    try:
        zk.set("/path", new_data, stat.version)
        break
    except BadVersionError:
        continue  # or pass

Also, do use pre-made recipes when you can, as they are already extensively debuged, and should treat all corner cases.

Upvotes: 0

thibr
thibr

Reputation: 617

In Java, you can can achieve what you want easily:

Stat stat = new Stat();
byte[] data = zk.getData("/path", null, stat));

This does read data and version information (in the stat object) in a single operation. When you write back the data, you pass the version number you got when you read it:

zk.setData("/path", data, stat.getVersion());

If there is a version mismatch, the method will throw KeeperException.BadVersionException, which gives you an optimistic lock.

Upvotes: 10

Related Questions