How to save an entity in GAE datastore only if it does not exist while preventing race conditions

馋奶兔 提交于 2019-12-02 07:45:20

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!