This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt on Threads

 
deepa durai
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy Deepa,

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.


Yours,
Bu.
 
deepa durai
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Burkhard,

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 ?



Thanks Deepa
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.



Yours,
Bu.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic