Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this multithreaded Java code work?

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?

like image 991
Vijay Avatar asked Sep 08 '26 11:09

Vijay


1 Answers

Think carefully about what happens in the following section.

account.setNumber(account.getNumber() + 1);

Even though both methods are separately synchronized, the operation as a whole isn't.

like image 154
Sridhar Avatar answered Sep 11 '26 01:09

Sridhar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!