How to save an entity in GAE datastore only if it

2019-03-03 19:54发布

I am trying to save an entity to Google App Engine Datastore only if it does not exist, if it does the thread should not continue.

Main issue is: I want to prevent any race conditions, such that if 2 threads are doing this at the same time only one would succeed in saving the entity.

I am not sure what is the best approach for this, would using Transactions work or one must rely on other solutions such as using Memcache

Please provide answer in low level API in java

2条回答
手持菜刀,她持情操
2楼-- · 2019-03-03 20:41

Assuming that the both threads are trying to save an entity with the same key, then this code:

datastore.add(entity);

will do what you want. If an entity already exists in datastore with the same key, then .add() will throw an exception.

查看更多
小情绪 Triste *
3楼-- · 2019-03-03 20:44

When calling Datastore from App Engine, the api is different. Use a transaction. First try to get() the entity to see if it's there. If not, put() the entity.

Here's some sample code that demonstrates transactions using the App Engine API: https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/appengine/datastore/src/test/java/com/example/appengine/TransactionsTest.java

查看更多
登录 后发表回答