• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronized - K&B sample

 
Anthony Karta
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I modified money withDrawal illustration in K&B book by putting makeWithDrawal() method in another class called AccountTrans.

But I got different behaviour/output, until I put that line which called makeWithDrawal() in synchronized(this) block.

anyone can explain why I need to synchronized on "this" object and
synchronized on "public void makeWithDrawal" doesn't work anymore?

hope make sense


 
Henry Wong
author
Marshal
Pie
Posts: 21008
77
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason synchronizing makeWithdraw() doesn't work is because you are instantiating a new AccountTrans object for each call. As for why "this" works is unclear -- you didn't show enough of the code.

The main takeaway is this... In order to have threads be single threaded during thread unsafe areas of code, they must all synchronized with the same object.

Henry
 
Anthony Karta
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry.

I am trying to mimic real scenario where 2 people access one account, that's why I create 2 instances of AccountTrans.

maybe it is not a good design (I'm trying to apply pojo). please advise.

below is a missing class (from my first post). Account class only contains set and get methods.

 
Henry Wong
author
Marshal
Pie
Posts: 21008
77
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason using the "this" object works is because every thread uses the *same* object. Both of your threads uses a same runnable. And in you run() method, the "this" refers to the runnable object.

Henry
 
Anthony Karta
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Henry Wong:
Both of your threads uses a same runnable. And in you run() method, the "this" refers to the runnable object.
Henry


I know there are 2 AccountTrans instance, But... I pass them the same Account instance.

If I want to remove "synchronized(this)" block, could you advise me how should I refactor them?

thanks again
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic