A simple example:
class Account{
private String account_name;
private String password;
private double balance;
public synchronized double getBalance(){
return balance;
}
public synchronized void setBalance(double add){
balance += add;
}
}
From my understanding that acquiring the lock associated with an object does not prevent other threads from accessing that object. They have to be the same lock to prevent accessing.
So if two person tried accessing the same account at different ATM, then it will create two different instances of this Account object, correct ? so then it’s not guarded with the same lock, right ?
lets say if Person A (Thread A) tried to save money into the account while at the same time Person B(Thread B) tried getting to total balance of the account.
How does it work ? Do they cache the Account while be using so it will return the same Account object when the next request comes in ?
Synchronized methods will lock the object instance. However, if there is a method, which is not synchronized concurrent access can happen.
ATM machines don’t access your account – the bank server does. The ATM machine is just a client. So accessing the same account from 2 different ATMs would be guarded by the bank server, which has only one instance of this account in it’s memory / database (probably protected by some locking mechanism and not written in Java).