Siva Reddy Vippala
Siva Reddy Vippala

Reputation: 211

How to avoid concurrent data modifications in GAE Datastore

Let’s say below is the GAE data store kind, where the need is to store two different players info into a single entity, how the data correctness can be maintained?

@Entity
public class Game
{
    id
    player1Id
    player2Id
    score1
    score2
}

Let say player1 wants to modify score1, he first reads the entity and modifies score1 and saves back into datastore.

Similarly player2 wants to modify score2, he as well first reads the entity and modifies score2 and saves back into datastore.

So having this functionality, there is a chance that both player1 and player2 try to modify the same entity and they could end up modifying the data incorrectly due to a dirty read.

Is there a way to avoid the dirty reads with GAE Data store to make sure the data correctness (or) avoid the concurrent modification?

Upvotes: 1

Views: 1203

Answers (2)

Andrei Volgin
Andrei Volgin

Reputation: 41089

You need to use Transactions, and then you have two options:

  1. Implement your own logic for transaction failures (how many times to retry, etc.)

  2. Instead of writing to the datastore directly, create a task to modify an entity. Run a transaction inside a task. If it fails, the App Engine will retry this task until it succeeds.

Upvotes: 3

Paul Collingwood
Paul Collingwood

Reputation: 9116

Transactions:

https://developers.google.com/appengine/docs/java/datastore/transactions

When two or more transactions simultaneously attempt to modify entities in one or more common entity groups, only the first transaction to commit its changes can succeed; all the others will fail on commit.

Upvotes: 3

Related Questions