Java Bank Account Synchronization example. Fail to see how solution works
-
01-06-2021 - |
Question
http://i.stack.imgur.com/D01ja.png
So, I'm reading a pdf about synchronization that shows the above example problem. A bit later, the following is presented, presumably as a solution:
class Account
{
private double balance;
public Account(double initialDeposit) {
balance = initialDeposit;
}
public synchronized double getBalance() {
return balance;
}
public synchronized void setBalance(double newBalance) {
balance = newBalance;
}
public synchronized void deposit (double amt) {
//essentially still multiple steps when in bytecode!
balance += amt;
}
I don't understand how this solves the problem. Maybe that's not what was intended, but it seems implied. I'm looking for some confirmation on whether it does or doesn't. }
Solution
The point of using the synchronized keyword is that only one thread can access the method at a time and the schema on your image becomes impossible.
But as discussed below, the presence of the setBalance method makes it possible to misuse the class and obtain an undesired output.
OTHER TIPS
The synchronized
keyword is making sure two threads cannot get into a synchronized block [on the same object] concurrently.
In your case, the 3 methods cannot be invoked on the same objects concurrently because each is holding a lock on this
when invoked.
So, nevertheless balance += amt;
is not atomic - it is synchronized, and thus it is not possible that the state will change during the the evaluation of this statement.
I'd be surprised if the PDF is proposing that as the final solution as it completely fails to solve the problem shown your image! Maybe it's showing you a naive attempt to solve the problem, by spraying synchronized keywords around a bit?
I would keep reading your PDF - And post your findings!