Given this Java code:
class Account {
private Integer number = 0;
public synchronized void setNumber(Integer number) {
this.number = number;
}
public synchronized Integer getNumber() {
return number;
}
}
class Client extends Thread {
Account account;
public Client(Account account) {
this.account = account;
}
public void run() {
for (int i = 1; i <= 1000; i++) {
account.setNumber(account.getNumber() + 1);
}
}
}
public class Run {
public static void main(String[] args) throws Exception {
Account account = new Account();
Client one = new Client(account);
Client two = new Client(account);
one.start();
two.start();
one.join();
two.join();
System.out.println("Exiting main");
System.out.println("account number value: " +account.getNumber());
}
}
What is the value of number when the main method completes? Is it 2000 or less than 2000? I am getting less than 2000. How can two threads call getNumer() or setNumber() from run() at the same time, given that each one is synchronized?
Think carefully about what happens in the following section.
Even though both methods are separately synchronized, the operation as a whole isn’t.