Hai, Please clear my doubt. In the following program, three threads accessing the same account.
My doubt is : As withdrawal method is a synchronized one,only one thread is allowed to make the withdrawal.After it finishes the withdrawal,second thread will withdraw.Eventhough the balance is Rs.90 after first thread's withdrwal,the second thread reads the balance as Rs.100.Why is this so? i)does the threads read the balance from the thread's local or from main memory? ii)After each thread making a withdrawal,will it store the balance in main memory or thread's local?when it gets stored in main memory?
iii) the balance variable is accessed from main memory or from thread's local each time it reads.
iv) what are the values in thread's local and will be in main memory?
Thanks in advance
moderator Bu: made one long line into to. [ August 23, 2007: Message edited by: Burkhard Hassel ]
Joined: Aug 25, 2006
welcome to the Ranch!
Eventhough the balance is Rs.90 after first thread's withdrwal,the second thread reads the balance as Rs.100.Why is this so?
The second thread has read the account before the first has made its withdrawal. This can be because the getAccount() method is not synchronized.
i) does the threads read the balance from the thread's local or from main memory?
No, it is not local. All three threads share one Runnable that has one Account that has one int named "balance". All threads operate on that one int.
ii) to iiii) -> see i)
Hope that helped.
all events occur in real time
Joined: May 08, 2007
Thanks for your answers.I have one more doubt.
If I create the account object inside the run method,what will happen?
I got answers like each thread has a copy of the balance variable,eventhough i make both the moethods synchronized.
Is this because of BankAccount account =new BankAccount(); is inside the run() method ?
Joined: Aug 25, 2006
If you create the account object in the run method it will be local. Anything that happens to the object will be lost when you leave the method. A second thread starting will encounter a brand new Account object. Does not make much sense.