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?
can ZooKeeper get znode data and znode data version (stat) in one single operation?
2.9k Views Asked by jedli2006 At
2
There are 2 best solutions below
0

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.
In Java, you can can achieve what you want easily:
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:If there is a version mismatch, the method will throw
KeeperException.BadVersionException
, which gives you an optimistic lock.