
Answer-first summary for fast verification
Answer: Get and put the entity in a transaction.
The code snippet provided demonstrates a common operation in Cloud Datastore where an account's balance is being credited. The current implementation lacks transactional safety, which could lead to race conditions if multiple operations attempt to modify the same account balance simultaneously. The correct improvement to suggest is to use a transaction for both getting and putting the entity (option B). This ensures that the operation is atomic and prevents concurrent modifications from causing inconsistencies. Options A, C, and D do not address the core issue of transactional integrity in the same direct manner as option B.
Author: LeetQuiz Editorial Team
Ultimate access to all questions.
No comments yet.
Which improvement would you recommend for the following Cloud Datastore code that adds a credit to an account balance?
public Entity creditAccount(long accountId, long creditAmount) {
Entity account = datastore.get(keyFactory.newKey(accountId));
account = Entity.builder(account)
.set("balance", account.getLong("balance") + creditAmount)
.build();
datastore.put(account);
return account;
}
public Entity creditAccount(long accountId, long creditAmount) {
Entity account = datastore.get(keyFactory.newKey(accountId));
account = Entity.builder(account)
.set("balance", account.getLong("balance") + creditAmount)
.build();
datastore.put(account);
return account;
}
A
Get the entity with an ancestor query.
B
Get and put the entity in a transaction.
C
Use a strongly consistent transactional database.
D
Don't return the account entity from the function.