Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

synchronized this vs field in Java

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading