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?
Great question.
This is the exact reason there are both synchronized methods and synchronized statements.
You can fine tune the synchronization, as to prevent unnecessary blocking within threads.
All synchronization does is allow for only one thread to execute the code-block at a time.
So, if you are using synchronized(this), then the entire instance will block other threads, on any invocation.
Whereas, if you are synchronizing on just a single variable, then only invocations on that object—or variable—will block.
Intrinsic Locks and Synchronization (The Java™ Tutorials > Essential Java Classes > Concurrency).
Here is a relevant excerpt.