I'm learning java concurrency and used a Bank Account that is shared among multiple people example to try to practice principles of concurrency.
This is my Account class.
public class Account(){
private int balance = 0;
public int getBalance(){ return balance}
public synchronized void deposit(int val){//..}
void synchronized void withdrawal(int val){//..}
}
deposit and withdrawal methods are synchronized because they directly modify the state of the Account object, so to avoid data corruption if multiple users try to change it at the same time.
On the other hand, getBalance()
does not change the state of the Account object. But I was thinking that if getBalance()
is called while a deposit or withdrawal is happening, it will return an outdated value. What is the standard practice, to synchronize or not to synchronize getBalance()
?