class BankAccount {
private int balance = 0;
int getBalance() {
synchronized(this) {
return balance;
}
}
void setBalance(int x) {
synchronized(this) {
balance = x;
}
}
void withdraw(int amount) {
synchronized(this) {
int b = getBalance();
if (amount > b)
throw...
setBalance(b– amount);
}
}
}
In withdraw there is "synchronized (this) …".
Let’s say I have in another method "synchronized (balance) …" (so a lock on balance and not on "this"), can that method be executed at the same moment withdraw is executed?
>Solution :
can that method be executed at the same moment withdraw is executed
Ignoring that you can’t sync on a primitive int and answering as if it were some object type, say Integer…
Then, yes, they can execute concurrently, since the two methods are using different locks, and thus neither prevents the other from executing.
It is irrelevant that one of the objects sync’d-on happens to contain the other object being sync’d-on.