Search code examples
javasynchronizationaccountbank

Java Bank Account Synchronization example. Fail to see how solution works


https://i.sstatic.net/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.