
Google Professional Cloud Developer
Get started today
Ultimate access to all questions.
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;
}
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;
}
Explanation:
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.